In this article, the example shares the specific code for python multi-threaded simultaneous accept and send for your reference, the details are as follows
''' Mimic qq can send and receive messages at the same time multithreaded ''' from socket import * from time import sleep import threading # Responsible for receiving data def recvData(): udpRecvSocket = socket(AF_INET,SOCK_DGRAM) # Use port 8080 by default myRecvPort = 8080 bindAddr = ('',8080) #try to prevent the port from being taken, and if it is, you have one chance to change it, and the system crashes anyway. try: #Binding Address (bindAddr) # Modifications after port is occupied except OSError: myRecvPort = int(input("Please enter the local acceptance port port:")) bindAddr = ('',myRecvPort) (bindAddr) Methods in the #socket module to get username and ip address. myIpAddr = gethostbyname(getfqdn(gethostname())) # Print local ip address and port used print("dispenseripaddress[{}],The port that accepts data is[{}]".format(myIpAddr,myRecvPort)) # Prevent anomalies caused by partial loss of received messages while True: try: recvData = (1024) # Maximum number of bytes is 1024 #recvData = ('GB2312') print('The output from the other computer is:{}'.format(recvData)) except error as e: print(e) # Responsible for sending data def sendData(): #To prevent the risk of simultaneous input with the above, so send data and pause for 10 seconds before running again. sleep(10) udpSendSocket = socket(AF_INET,SOCK_DGRAM) #The user inputs the receiver information and stores it in sendAddr. sendIpAddr = input('Please enter the recipient's ip address:') sendPort = int(input('Please enter the recipient's port:')) sendAddr = (sendIpAddr,sendPort) while True: sendData = input('Please enter the content to be sent:') ((),sendAddr) # Responsible for multi-threading def main(): # Multi-threading two methods at the same time t1 = (target=recvData) t2 = (target=sendData) () () () () if __name__ == '__main__': main()
This is the whole content of this article.