ThreadingMixIn和ForkingMixIn类

异步混合:

为了建立异步处理机制,需要使用ThreadingMixIn和ForkingMixIn类。

以下是一个使用ThreadingMixIn类的示例:

<strong>import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver</strong><span style="color:#cc0000;">.BaseRequestHandler):
</span>
   <span style="color:#ff0000;"> def handle(self):
</span><strong>        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("{}: {}".format(</strong><span style="color:#ff0000;">cur_thread.name, data</span><strong>), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn,</strong> <span style="color:#ff0000;"><strong>socketserver.TCPServer):</strong>
</span><strong>    pass

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    try:
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: {}".format(response))
    finally:
        sock.close()

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0</strong>

    <span style="color:#ff0000;">server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
</span><span style="color:#ff0000;">    ip, port = server.server_address
</span><strong>
    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(</strong><span style="color:#ff0000;">target=server.serve_forever</span><strong>)
    # Exit the server thread when the main thread terminates</strong>
    <span style="color:#ff0000;">server_thread.daemon = True
    server_thread.start()
</span><strong>    print("Server loop running in thread:", server_thread.name)</strong>

    <span style="color:#ff0000;">client(ip, port, "Hello World 1")
    client(ip, port, "Hello World 2")
    client(ip
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值