gpt4 book ai didi

python - 在 Python 3 中使用流选择器终止循环

转载 作者:行者123 更新时间:2023-12-01 03:17:58 26 4
gpt4 key购买 nike

我在线程中运行了一些代码,以等待使用套接字传入的客户端连接:

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() 会阻塞,直到读取到某些内容。我也考虑过使用选择器的错误处理机制,但我不一定想在错误/异常期间关闭服务器。

似乎我需要选择器从第二个流中读取,其中包含一个特殊的命令来停止循环,但这似乎过于复杂。任何建议将不胜感激!

最佳答案

既然您已经说过可以使用 while self.flag 而不是 while True,您可以指定一个超时 参数,as explained in the docs 。只需确保在输入 for key, _ in events: 循环

之前检查您的数据

关于python - 在 Python 3 中使用流选择器终止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com