TCP协议中的socket一次只能和一个客户端通信,然而socketserver可以实现和多个客户端通信。
它是在socket的基础上进行了一层封装,底层还是调用的socket
# 服务端 import socketserver class Myserver(socketserver.BaseRequestHandler): def handle(self): while 1: from_client_msg = self.request.recv(1024) print(from_client_msg.decode('utf-8')) msg = input('服务器说:') self.request.send(msg.encode('utf-8')) if __name__ == '__main__': ip_port = ('127.0.0.1', 8001) server = socketserver.ThreadingTCPServer(ip_port, Myserver) server.serve_forever()
# 客户端 import socket client = socket.socket() client.connect(('127.0.0.1', 8001)) while 1: msg = input('客户端说:') client.send(msg.encode('utf-8')) from_server_msg = client.recv(1024) print(from_server_msg.decode('utf-8'))