我是否必须明确释放/取消绑定套接字才能重用它?我正在考虑使用close()
,但我看到了一些选项,例如tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
。我必须使用它还是close()
足够?
有没有办法确保端口对于新绑定是免费的?
TorPorts = {}
def port_setup(workers):
for worker in range(workers):
for i in range(2):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind(('', 0))
port = tcp.getsockname()[1]
print("{0} port {1}, tcp {2}".format(i,port,tcp))
if not TorPorts.has_key(worker):
TorPorts[worker] = {0:{},1:{}}
TorPorts[worker][i] = {"port":port,"tcp":tcp}
# do some programing
# close ports I s this enough?
for thread,ports in TorPorts[0].items():
tcp_port = ports["tcp"]
tcp_port.close()
答案 0 :(得分:2)
最好使用tcp_port.close()
socket.SO_REUSEADDR
在某些情况下可能会失败。如果发生这种情况,则在WAIT_TIME
完成之前,您无法重新绑定到同一端口。