In the socket, if created directly, only one user's request can be accepted
Need to implement handle method in Socketserver, can implement multi-process concurrent access
The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. That is, when each client requests a connection to the server, the socket server is creating a "thread" or "process" dedicated to all requests from the current client.
1. Create a inherit from Socketserver. Baserequesthandler class, a method named handle must be defined in the class
2. Start Threadingtcpserver
import socketserverclass MyServer(socketserver.BaseRequestHandler): def handle(self): conn = self.request conn.sendall("我是一个多线程".encode()) Flag = True while Flag: data = conn.recv(1024) if data.decode() == "exit": Flag = False conn.sendall(data)if __name__ == "__main__": server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8009),MyServer) server.serve_forever()
客户端直接使用原来的客户端代码即可。
Threadingtcpserver
The Soket server implemented by Threadingtcpserver creates a "thread" for each client that is used to interact with the client.
Python socket multithreading and multi-process