流程
1、处理多个客户端,初始化ThreadingTCPServer实例。
2、设置绑定的IP地址和端口和处理类。
3、使用StreamRequestHandler。
(使用流程的请求处理程序类似于file-like对象,提供标准文件接口简化通信过程),重写中的handle方法,获取请求数据,将数据返回客户端
实例
from socketserver import BaseRequestHandler, TCPServer class EchoHandler(BaseRequestHandler): def handle(self): print("Got Connection From: %s" % str(self.client_address)) while True: msg = self.request.recv(8192) if not msg: break self.request.send(msg) if __name__ == "__main__": server = TCPServer(("", 5000), EchoHandler) server.serve_forever()
from socketserver import StreamRequestHandler, TCPServer, ThreadingTCPServer import time class EchoHandler(StreamRequestHandler): def handle(self): print("Got Connection Address: %s" % str(self.client_address)) for line in self.rfile: print(line) self.wfile.write(bytes("hello {}".format(line.decode('utf-8')).encode('utf-8'))) if __name__ == "__main__": serv = ThreadingTCPServer(("", 5000), EchoHandler) serv.serve_forever()
以上就是python socketserver处理客户端的流程,希望对大家有所帮助。更多Python学习指路:
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。