1. socketserver 多线程用的
例
import socket import timeclient=socket.socket() client.connect(("127.0.0.1",9000))while 1:cmd=input("请输入指令")client.send(cmd.encode("utf-8"))from_server_msg=client.recv(1024).decode("utf-8")print(from_server_msg) client.close()
import socketserverclass Myserver(socketserver.BaseRequestHandler):def handle(self):while 1: #记住,这边的self.request相当于conn,管道,接收数据from_client_cmd=self.request.recv(1024)print(from_client_cmd.decode("utf-8"))server_msg=input("服务端说:")self.request.send(server_msg.encode("utf-8"))if __name__=="__main__":# 设置allow_reuse_address允许服务器重用地址socketserver.TCPServer.allow_reuse_address = Trueip_port=("127.0.0.1",9000)# 创建一个server, 将服务地址绑定到"127.0.0.1",9000server=socketserver.ThreadingTCPServer(ip_port,Myserver)让服务器永远运行下去,除非强强行停止server.serve_forever()