在 Python 3 中使用流选择器终止循环
Terminating loop using stream selector in Python 3
我在线程中有一些代码 运行 来等待使用套接字的传入客户端连接:
import threading
import socket
import selectors
class Server(threading.Thread):
def __init__(self):
# instantiate socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket
self.socket.bind(("localhost", 50000))
def run(self):
# create selector to interface with OS
sel = selectors.DefaultSelector()
# register the connection handler for when a client connects
sel.register(self.socket, selectors.EVENT_READ, self.handle_connection)
while True:
events = sel.select()
for key, _ in events:
# run the callback
key.data()
def handle_connection(self):
# handle a request on the socket
data = self._socket.accept()
# do stuff with data...
def stop(self):
# what to do?
pass
此代码进入 while True
循环并调用 sel.select()
,它会阻塞直到从 self._socket
读取某些内容,然后调用回调 self.handle_connection
(与我的问题)。这很好用,但我还想做的是使用线程的 stop
方法中断 while True
循环,以便我在其他地方的主程序循环可以停止线程并关闭服务器优雅。
我不能只检查像 while self.running:
这样的标志,因为 sel.select()
在读取某些内容之前会阻塞。我也想过使用选择器的错误处理机制,但我不一定想在 errors/exceptions.
期间关闭服务器
似乎我需要选择器从第二个流中读取,其中包含一个特殊的命令来停止循环,但这似乎过于复杂。如有任何建议,我们将不胜感激!
既然您已经说过您可以使用 while self.flag
而不是 while True
,您可以指定一个 timeout
参数,as explained in the docs。请确保在进入 for key, _ in events:
循环
之前检查您的数据
我在线程中有一些代码 运行 来等待使用套接字的传入客户端连接:
import threading
import socket
import selectors
class Server(threading.Thread):
def __init__(self):
# instantiate socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket
self.socket.bind(("localhost", 50000))
def run(self):
# create selector to interface with OS
sel = selectors.DefaultSelector()
# register the connection handler for when a client connects
sel.register(self.socket, selectors.EVENT_READ, self.handle_connection)
while True:
events = sel.select()
for key, _ in events:
# run the callback
key.data()
def handle_connection(self):
# handle a request on the socket
data = self._socket.accept()
# do stuff with data...
def stop(self):
# what to do?
pass
此代码进入 while True
循环并调用 sel.select()
,它会阻塞直到从 self._socket
读取某些内容,然后调用回调 self.handle_connection
(与我的问题)。这很好用,但我还想做的是使用线程的 stop
方法中断 while True
循环,以便我在其他地方的主程序循环可以停止线程并关闭服务器优雅。
我不能只检查像 while self.running:
这样的标志,因为 sel.select()
在读取某些内容之前会阻塞。我也想过使用选择器的错误处理机制,但我不一定想在 errors/exceptions.
似乎我需要选择器从第二个流中读取,其中包含一个特殊的命令来停止循环,但这似乎过于复杂。如有任何建议,我们将不胜感激!
既然您已经说过您可以使用 while self.flag
而不是 while True
,您可以指定一个 timeout
参数,as explained in the docs。请确保在进入 for key, _ in events:
循环