Python绑定套接字:关闭套接字后,“地址已在使用中”

时间:2019-06-18 21:03:37

标签: python sockets tcp client

我知道已经有一个类似的问题,但是没有一种解决方案可以解决我的问题。通过ssh,我正在使用

在远程客户端上启动脚本
nohup python script.py &

此脚本包含以下内容:

TCP_PORT = 5005
host = ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(40)
s.bind((host, TCP_PORT))
s.listen(0)
c, addr = s.accept()

...some code...

try:
    while True:
        c.send(str(1).ljust(16).encode())
except Exception as e:
    print("exiting main")
    print(e)
    c.close()
    s.close()

当我在e行中两次运行代码时,第二次我总是遇到上述错误。 python输出的日志:

exiting main
[Errno 32] Broken pipe

Traceback (most recent call last):
  File "LogImages.py", line 204, in <module>
    main(interv)
  File "LogImages.py", line 114, in main
    s.bind((host, TCP_PORT))
OSError: [Errno 98] Address already in use

因此,很明显,该过程将调用c.close()和s.close()。那么如何继续使用该地址?

1 个答案:

答案 0 :(得分:1)

关闭套接字只会将句柄释放到任何基础连接。该实现仍需要花费一些时间才能完成连接的有序关闭,在此期间,该地址仍在使用中。

例如,如果您有一个活动的连接,而另一端没有从该连接中读取数据,则该实现将为其提供时间来读取已发送的数据。在此期间,该地址仍在使用中。