• Python网络编程 —— 并发的 SocketServer


    1、并发的 socketserver

    实现程序的并发执行

    Server

    import time
    from socketserver import BaseRequestHandler,ThreadingTCPServer
    # BaseRequestHandler 基础请求操作符
    # ThreadingTCPServer 线程实现的基于tcp协议的server
    class Myserver(BaseRequestHandler):   # 创建一个Myserver类继承BaseRequestHandler
        def handle(self):
            n = 0
            while True:
                self.request.send(str(n).encode('utf-8'))  # self.request == conn(server的IP)
                n += 1
                time.sleep(0.5)
    
    server = ThreadingTCPServer(('127.0.0.1',9001),Myserver)  # 创建一个server将服务地址绑定到127.0.0.1:9001
    server.serve_forever()    # 让server永远运行下去,除非强制停止程序
    

    ThreadingTCPServer源码的继承关系梳理

    Client 1

    import socket
    
    sk = socket.socket()
    sk.connect(('127.0.0.1',9001))
    
    while True:
        ret = sk.recv(1024)
        print(ret)
    

    Client 2

    import socket
    
    sk = socket.socket()
    sk.connect(('127.0.0.1',9001))
    
    while True:
        ret = sk.recv(1024)
        print(ret)
    
  • 相关阅读:
    Python并发编程之多进程(实战)
    ThreadPoolExecutor源码分析
    JDK 1.8 JVM的变化
    JDK1.8 hashMap源码分析
    Spring解决循环依赖
    spring
    实现一个可重入锁和不可重入锁
    B树与B+树
    WebMagic
    Java高频面试题
  • 原文地址:https://www.cnblogs.com/caiyongliang/p/14000572.html
Copyright © 2020-2023  润新知