0
我有一个多线程程序,其实例5个插槽目的如下:Python如何关闭在线程中实例化的套接字?
class myThread (threading.Thread):
def __init__(self, pid, port_num, restart):
threading.Thread.__init__(self)
self.hostname = '127.0.0.1'
self.pid = pid
self.port_num = port_num
self.ID = pid
self.restart = restart
self.delay = pid*4*1000
def run(self):
try:
s = timer(self.hostname, self.port_num, self.pid)
#print "Socket S run"+str(s)
sendToSocket(self.pid, s, self.t, self.ID)
except Exception as e:
raise
在这里,函数timer
用于实例化一个线程以下列方式:
def timer(host, port, pid):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
timed = pid * 4 * 100
s.settimeout(timed)
s.bind((host, port))
s.listen(5)
return s
我要终止的一个在特定端口的插座称为5005. 上述示例中的pid从5001变为5005.
我想关闭一个插座之间 - 说5005。
所以我用这个方法:
s = socket.socket()
s.connect(('127.0.0.1', 5005))
s.close()
但套接字不会关闭。
我需要从外部函数调用上述过程。
总之,如果没有绑定到端口5005的套接字,我想关闭套接字,并使其无法使我们就会得到一个Port not found exception.
[在Python线程关闭监听套接字(http://stackoverflow.com/questions/16734534/close-listening-socket-in-python-thread)的可能的复制 – Dillanm
作为your'class MyThread的'举行'.port_num','myThread_instance.s.close()'不工作? – stovfl