简体   繁体   English

如何在Python中停止套接字线程?

[英]How can i stop a socket thread in Python?

In Python 3.3.3, i create a thread to listen some connection to the socket.It likes this: 在Python 3.3.3中,我创建了一个线程来侦听与套接字的某些连接。它是这样的:

import threading
import socket
import time

Host = ''
Port = 50000

flag = False

class ServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def run(self):
        try:
            self._sock.bind((Host, Port))
            self._sock.listen(5)
            while True:
                conn, addr = self._sock.accept()
                print('Connected by', addr)
        except socket.error as msg:
            print(msg)
        except Exception as e:
            print(str(e))
        finally:
            self._sock.close()
    def exit(self):
        self._sock.close()

def TargetFunc(vlock):
    vlock.acquire()
    flag = True
    vlock.release()

def main():
    sthread = ServerThread()
    sthread.start()
    vlock = threading.Lock()
    time.sleep(10)
    vthread = threading.Thread(target = TargetFunc, args = (vlock, ))
    vthread.start()
    while True:
        vlock.acquire()
        if flag:
            sthread.exit()
            vlock.release()
            break
        vlock.release()
    sthread.join()
    vthread.join()

if __name__ == '__main__':
    main()

There are two threads, one is listening socket, the other is to set a flag. 有两个线程,一个是侦听套接字,另一个是设置标志。 When the flag is True, close the socket, then raise a socket error and catch it, so the listening socket terminates.But why it does not work this. 当该标志为True时,关闭套接字,然后引发套接字错误并捕获它,以便监听套接字终止,但是为什么它不起作用。

Thanks! 谢谢!

self._sock.accept() is blocking. self._sock.accept()正在阻止。 So it will wait until somebody connects. 因此它将等待直到有人连接。 You should use a nonblocking variant (or blocking but with a time-out). 您应使用非阻塞变体(或阻塞但超时)。 So that you can check the exit conditions. 这样就可以检查退出条件。

Alternatively you could force an exception in the ServerThread. 或者,您可以在ServerThread中强制执行异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM