python线程监控,在python线程中关闭监听套接字

I have a problem trying to learn about sockets for network communication. I have made a simple thread that listens for connections and creates processes for connecting clients, my problem though is that I can't get the thread to join properly as I haven't found a way to cancel the socket.accept()-call when I want to quit the program.

My code looks like this;

class ServerThread( threading.Thread ):

def __init__(self, queue, host, port):

threading.Thread.__init__(self)

self.queue = queue

self.running = True

self.hostname = host

self.port = port

def run(self):

self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.socket.bind((self.hostname, self.port))

self.socket.listen(1)

while self.running:

try:

conn, address = self.socket.accept()

process = Process(target=server_slave, args=(conn, address, self.queue))

process.daemon = True

process.start()

except socket.timeout:

pass

def stop(self):

self.running = False

self.socket.close()

I have managed to get the program to close by setting self.setDaemon(True) and just exiting the main program, handing everything to the great garbage collector - but that seems like a bad solution. I've also tried setting a timeout for the socket but that results in getting [Errno 35] Resource temporarily unavailable (regardless of the actual timeout, even when I set it to years...).

What am I doing wrong? Have I designed the thread in a dumb way or have I missed something about accepting connections?

解决方案

One way to get the thread to close seems to be to make a connection to the socket, thus continuing the thread to completion.

def stop(self):

self.running = False

socket.socket(socket.AF_INET,

socket.SOCK_STREAM).connect( (self.hostname, self.port))

self.socket.close()

This works, but it still feels like it might not be optimal...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>