Serial processing of socket communication via the socket module in the "Python---socket module"
In Python, concurrent communication can be achieved through the Socketserver module, while the Socketserver can be implemented concurrently through IO multiplexing and multi-process, multithreading
The following is an example of using the Socketserver module for multithreading concurrent processing requests
Server-side
#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Zhoufeng'ImportSocketserverclassMyServer (Socketserver. Baserequesthandler):#Custom request processing class, inherited from Baserequesthandler class defHandle (self):#override the handle method, the handle method in Baserequesthandler is emptyConn=self.request#establish a communication connection similar to the Accept method in the socket moduleConn.sendall (Bytes ('Welcome to call 10086, please enter XXX', encoding='UTF8'))#send data in bits form whileTrue:data=CONN.RECV (1024)#Receive Data Print('[%s] says:%s'% (Self.client_address,data.decode ()))#Client_address represents the client addressConn.sendall (Data.upper ())#Send Dataif __name__=='__main__': #the Threadingtcpserver class has two parameters, a socket tuple, and a request processing class #socket tuple (' 127.0.0.1 ', 8009) #the request handling class here is our custom MyServer #the request processing class can also be a derived class of Baserequesthandler Streamrequesthandler and Datagramrequesthandler #with each request, a server instance (which can be understood as a thread) is generated .Server=socketserver. Threadingtcpserver (('127.0.0.1', 8009), MyServer)#what is the function of the Serve_forever method? Server.serve_forever ()
View Code
Client
#!/usr/bin/env python#-*-coding:utf-8-*-__author__='Zhoufeng'ImportSocketip_port=('127.0.0.1', 8009) s=Socket.socket () s.connect (ip_port) welcome_msg=S.RECV (1024)Print("From server:", Welcome_msg.decode ()) whileTrue:#Send MessageSend_data=input (">>:"). Strip ()ifLen (send_data) ==0:Continues.sendall (bytes (send_data,encoding='UTF8')) #Receive MessageRECV_DATA=S.RECV (1024) Print(Str (recv_data,encoding='Utf-8') ) S.close ()
View Code
Python---socketserver module