socket.error: [Errno 98] Address already in use的解決方案

參考python官網手冊

Running an example several times with too small delay between executions, could lead to this error:

socket.error: [Errno 98] Address already in use
This is because the previous execution has left the socket in a TIME_WAIT state, and can’t be immediately reused.

There is a socket flag to set, in order to prevent this, socket.SO_REUSEADDR:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

通過設置socket.SO_REUSEADDR參數,可以使端口在處於TIME_WAIT狀態時重新被啓用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章