socketserver内部使用IO多路复用及多线程和多进程,从而实现并发处理多个客户端请求的socket服务端。即:每个客户端请求连接到服务器时,socket服务端都会在服务器创建一个线程或者进程专门负责处理当前客户端的所有请求。
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): while True: try: self.data = self.request.recv(1024).strip() print(self.data) if not self.data:break self.request.sendall(self.data.upper()) except ConnectionResetError as e: print(e) break if __name__ == '__main__': HOST, PORT = 'localhost', 6969 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) server.serve_forever()
import socket cs = socket.socket() cs.connect(('localhost', 6969)) while True: sen = input('>>:').strip() if sen == 'q': cs.close() break cs.send(sen.encode('utf-8')) rec = cs.recv(1024) print(rec.decode())