在python线程中关闭监听套接字 [英] Close listening socket in python thread

查看:545
本文介绍了在python线程中关闭监听套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试了解网络通信套接字时遇到问题.我创建了一个简单的线程来侦听连接并创建用于连接客户端的进程,但是我的问题是我无法找到合适的线程,因为我还没有找到取消socket.accept()-call的方法当我想退出程序时.

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.

我的代码如下:

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()

我已经设法通过设置self.setDaemon(True)并退出主程序来关闭程序,然后将所有内容交给出色的垃圾收集器-但这似乎是一个糟糕的解决方案.我也尝试过为套接字设置超时,但这会导致得到[Errno 35] Resource temporarily unavailable(无论实际超时如何,即使我将其设置为年...).

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...

这篇关于在python线程中关闭监听套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆