我想编写一个接受 tcp 连接的服务器,但我不想在调用 socket.accept() 时阻塞主线程,所以我想将网络放在不同的位置线。我已经看到在 Python 中无法中断线程,现在我想知道如何正确停止 socket.accept() 调用。
我想要的解决方案类似于 Java,例如:
class TcpServer:
def waitForConnection():
try:
conn, addr = socket.accept()
except ThreadInterrupt:
# Close server ...
不幸的是,这个“ThreadInterrupt”并不存在。那么,我怎样才能实现这种行为呢?预先感谢每个提示。
请您参考如下方法:
您可以将套接字设置为非阻塞操作,并等待旧的 select 调用为它准备好 accept(当它变得可读时 第一次)。附加值是您可以监听另一个文件 描述符,例如管道,这样您就可以进行特权通信 channel 与你的线程,你可以随时退出线程:
import select
import socket
import os
class TcpServer:
def __init__(self, ...):
self.r_channel, self.w_channel = os.pipe()
self.socket = ...
def waitForConnection(self):
rfds, _, _ = select.select([self.socket.fileno(), self.r_channel],[],[])
if self.r_channel in rfds:
# close server
...
self.socket.accept() # this won't block
# if you want to interrupt waitForConnection, from main thread:
os.write(tcp_server_object.w_channel, '!') # write something, just to wake up the select call
