• 技术文章 >Python技术 >Python基础教程

    python socketserver处理客户端的流程

    小妮浅浅小妮浅浅2021-08-09 10:19:36原创3061

    流程

    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学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python socketserver
    品易云
    上一篇:python线程阻塞的解决 下一篇:python socket连接客户端的方法

    相关文章推荐

    • python统计字符串字符出现次数• python输入身份证号输出出生年月• python计数排序法是什么• python希尔排序的使用原理• python归并排序是什么• python归并排序的实现原理• python使用choice生成随机数• python binomial生成二项分布随机数• python二项分布的概率使用• python正态分布中的normal函数• python tqdm有哪些用法• python自定义进度条显示信息• python线程阻塞的解决

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网