ThreadingTCPServer的用法

2020年7月19日 / 27次阅读 / Last Modified 2020年7月19日
socket

ThreadingTCPServer来自python标准库中的socketserver.py模块,我已经用它做了3个服务器了,很好用,特此总结。

ThreadingTCPServer,就是线程化的TCP服务器,客户端发起的TCP连接,在服务器侧,都是一个个的线程。显然,这个ThreadingTCPServer是异步多线程的框架模型。

创建Server:

with socketserver.ThreadingTCPServer(
                    ('0.0.0.0', cm.TCP_PORT),
                    myTcpHandler) as tcp_server:
        tcp_server.daemon_threads = True
        #tcp_server.allow_reuse_address = True
        tcp_server.serve_forever()

0.0.0.0表示在所有接口上监听;

daemon_threads = True,表示如果服务器停止,所有线程会自行了断;

myTcpHandler继承自socketserver.BaseRequestHandler类,这个类的框架代码如下:

class BaseRequestHandler:

    """Base class for request handler classes.

    This class is instantiated for each request to be handled.  The
    constructor sets the instance variables request, client_address
    and server, and then calls the handle() method.  To implement a
    specific service, all you need to do is to derive a class which
    defines a handle() method.

    The handle() method can find the request as self.request, the
    client address as self.client_address, and the server (in case it
    needs access to per-server information) as self.server.  Since a
    separate instance is created for each request, the handle() method
    can define other arbitrary instance variables.

    """

    def __init__(self, request, client_address, server):
        self.request = request
        self.client_address = client_address
        self.server = server
        self.setup()
        try:
            self.handle()
        finally:
            self.finish()

    def setup(self):
        pass

    def handle(self):
        pass

    def finish(self):
        pass

从这段代码可以看出,对于每一个TCP连接线程,先setup,然后handle,不管有误异常,最后总会finish。我们自己的代码,主要就是重写handle和finish这两个函数,当然也可以在继承类中添加自己的函数。

就这样简简单单,一个异步多线程TCP服务器就能搭起来,python救命啊~~!

-- EOF --

本文链接:https://www.pynote.net/archives/2297

留言区

电子邮件地址不会被公开。 必填项已用*标注


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top