socketserver实现并发原理:给每一个前来链接的客户端开启一个线程执行通信。也就是给每一个连接“配备”了一个管家。
下面用一个简单的示例来演示socketserver实现并发(一个服务端,两个客户端):
服务器端:
1 # Author : Kelvin 2 # Date : 2019/2/3 21:51 3 import socketserver 4 from socket import * 5 6 ip_conf = ("127.0.0.1", 8888) 7 buffer_capcity = 1024 8 9 10 class Mysocket(socketserver.BaseRequestHandler): 11 def handle(self): 12 print(self.request) 13 print(self.client_address) 14 15 while True: 16 data = self.request.recv(buffer_capcity).decode("utf8") 17 print("服务器收到信息:%s" % data) 18 self.request.send("服务器收到信息!".encode("utf8")) 19 20 21 if __name__ == "__main__": 22 s = socketserver.ThreadingTCPServer(ip_conf, Mysocket) 23 s.serve_forever()
客户端一:
1 # Author : Kelvin 2 # Date : 2019/2/3 21:51 3 from socket import * 4 5 ip_conf = ("127.0.0.1", 8888) 6 buffer_capcity = 1024 7 client = socket(AF_INET, SOCK_STREAM) 8 client.connect(ip_conf) 9 while True: 10 client.send(input("客户端1输入:").encode("utf8")) 11 data = client.recv(buffer_capcity).decode("utf8") 12 print(data)
客户端二:
1 # Author : Kelvin 2 # Date : 2019/2/3 21:51 3 from socket import * 4 5 ip_conf = ("127.0.0.1", 8888) 6 buffer_capcity = 1024 7 client = socket(AF_INET, SOCK_STREAM) 8 client.connect(ip_conf) 9 while True: 10 client.send(input("客户端2输入:").encode("utf8")) 11 data = client.recv(buffer_capcity).decode("utf8") 12 print(data)
打印结果:
服务器输出:
客户端一:
客户端二: