Python 套接字服务器
Posted
技术标签:
【中文标题】Python 套接字服务器【英文标题】:Python SocketServer 【发布时间】:2011-04-21 06:25:41 【问题描述】:在收到某个消息“退出”后,如何在SocketServer
中调用shutdown()
?据我所知,调用serve_forever()
会阻塞服务器。
谢谢!
【问题讨论】:
【参考方案1】:使用来源,卢克!
摘自 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()
【讨论】:
不错的答案,但 +1 表示“使用源代码,卢克!”。现在,如果只有 OP 的名字是 Luke....【参考方案2】:不,serve_forever
会定期检查标志(默认为 0.5 秒)。调用 shutdown 将引发此标志并导致 serve_forever 结束。
【讨论】:
以上是关于Python 套接字服务器的主要内容,如果未能解决你的问题,请参考以下文章
python python中的套接字服务器使用select函数
Python网络编程利用Python进行TCPUDP套接字编程