Python SocketServer使用指南

6 投票
2 回答
4033 浏览
提问于 2025-04-16 05:01

我该怎么在收到特定消息“exit”后,在一个SocketServer中调用shutdown()呢?我知道,调用serve_forever()会让服务器一直处于运行状态,无法继续其他操作。

谢谢!

2 个回答

4

不,serve_forever 这个功能会定期检查一个标志(默认是每0.5秒检查一次)。当你调用关闭功能时,这个标志会被设置为真,从而让 serve_forever 停止运行。

6

用源代码来解决问题,卢克!

来自 SocketServer.py 的摘录:

   def serve_forever(self, poll_interval=0.5):
        """Handle one request at a time until shutdown.

        Polls for shutdown every poll_interval seconds. Ignores
        self.timeout. If you need to do periodic tasks, do them in
        another thread.
        """
        self.__is_shut_down.clear()
        try:
            while not self.__shutdown_request:
                # XXX: Consider using another file descriptor or
                # connecting to the socket to wake this up instead of
                # polling. Polling reduces our responsiveness to a
                # shutdown request and wastes cpu at all other times.
                r, w, e = select.select([self], [], [], poll_interval)
                if self in r:
                    self._handle_request_noblock()
        finally:
            self.__shutdown_request = False
            self.__is_shut_down.set()

    def shutdown(self):
        """Stops the serve_forever loop.

        Blocks until the loop has finished. This must be called while
        serve_forever() is running in another thread, or it will
        deadlock.
        """
        self.__shutdown_request = True
        self.__is_shut_down.wait()

撰写回答