Python SocketServer
一、Server端
#!/usr/bin/python # -*- coding : utf-8 -*- # 作者: Presley # 时间: 2018-11-12 # 邮箱:2536450988@qq.com # 这是我用来练习socketserver 的测试脚本 import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): print("New Conn:", self.client_address) while True: try: data = self.request.recv(1024) if not data:break print("Client Says:",data.decode("utf-8")) self.request.send(data) except: continue if __name__ == "__main__": HOST,PORT = "localhost",50007 #把刚才写的类当作一个参数传给ThreadingTCPServer这个类,下面的代码就创建了一个实例 server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler) #启动这个server,这个server会一直运行,除非按ctrl-C 停止 server.serve_forever()
二、Client端
#!/usr/bin/python # -*- coding : utf-8 -*- # 作者: Presley # 时间: 2018-11-12 # 邮箱:1209989516@qq.com # 这是我用来练习socketserver 的测试脚本 import socket ip_port = ("127.0.0.1",50007) sk = socket.socket() sk.connect(ip_port) while True: msg = input(">>:").strip() if not msg:continue sk.sendall(msg.encode("utf-8")) server_reply = sk.recv(1024) print("服务器端说:",server_reply.decode("utf-8")) sk.close()