在Python 3.3.3中,我创建了一个线程来监听与socket的连接。它喜欢这个:
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()
有两个线程,一个是侦听套接字,另一个是设置标志。当标志为True时,关闭套接字,然后引发套接字错误并捕获它,因此监听套接字终止。但是为什么它不起作用。
谢谢!
答案 0 :(得分:3)
self._sock.accept()
正在阻止。所以它会等到有人连接。您应该使用非阻塞变体(或阻止但具有超时)。这样你就可以检查退出条件了。
或者,您可以在ServerThread中强制执行异常。