Socketserver
Python Road "Nineth": Python Foundation the Socket module is a single process and can only accept connections and requests from one client, and only when the client is disconnected can it accept connections and requests from other clients. Of course, we can also use the multi-threading module of Python to write a socket that can receive multiple client connections and requests at the same time. But this is not necessary, because the Python standard library has built a multi-threaded socket module Socketserver, we directly call on it, there is absolutely no need to repeat the wheel.
We simply need to retrofit the previous socket demo service side, the client does not change
1 ImportSocketserver2 classMyserver (socketserver. Baserequesthandler):3 " "4 defines a class to inherit from Socketserver. Baserequesthandler5 " "6 defhandle (self):7 " "8 overriding the handle method, which is very critical when the server receives a request from the client, will change the client individually9 starts a thread and calls the method to process the client's requestTen " " One Print('New Conn:', self.client_address) A whileTrue: - " " - loop receive the data sent by the client, here can be a the For example, if the received content is empty or an exception occurs and its - he introduced logic to exit the loop - " " -data = SELF.REQUEST.RECV (1024) + Print('Client say:%s'%Data.decode ()) - self.request.send (data) + A at if __name__=='__main__': -Ip_port = ('127.0.0.1', 9999)#define the IP address and port of the listener -Server = Socketserver. Threadingtcpserver (Ip_port, Myserver)#Create the Soeketserver object, the Threadingtcpserver method receives two parameters, one is the listening IP address and the port, the other is the class that we just created -Server.serve_forever ()#Start the service
Socketserver is the use of multi-threaded and class technology to the native socket module is encapsulated
Python Road "Nineth": Python Foundation (--socket) server