我是否必须显式释放/取消绑定套接字才能重用它?我正在考虑使用,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()
Run Code Online (Sandbox Code Playgroud)
使用起来比较好tcp_port.close(),但socket.SO_REUSEADDR在某些场景下可能会失败。如果发生这种情况,您无法重新绑定到同一端口,直到WAIT_TIME完成为止。