python SocketServer.ThreadingTCPServer - 程序重启后无法绑定到地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2274320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:14:23  来源:igfitidea点击:

SocketServer.ThreadingTCPServer - Cannot bind to address after program restart

pythonlinuxsocketstcpserver

提问by Justin Ethier

As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted:

作为cannot-bind-to-address-after-socket-program-crashes的后续,我在程序重新启动后收到此错误:

socket.error: [Errno 98] Address already in use

socket.error: [Errno 98] 地址已被使用

In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server:

在这种特殊情况下,程序不是直接使用套接字,而是启动自己的线程 TCP 服务器:

httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()

How can I fix this error message?

如何修复此错误消息?

回答by Lynn

The above solution didn't work for me but this one did:

上面的解决方案对我不起作用,但这个解决方案:

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
   server.serve_forever()

回答by Justin Ethier

In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)may be called from the TCPServer class when the allow_reuse_addressoption is set. So I was able to solve it as follows:

在这种特殊情况下,.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)可以在allow_reuse_address设置选项时从 TCPServer 类调用。所以我能够解决它如下:

httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler, False) # Do not automatically bind
httpd.allow_reuse_address = True # Prevent 'cannot bind to address' errors on restart
httpd.server_bind()     # Manually bind, to support allow_reuse_address
httpd.server_activate() # (see above comment)
httpd.serve_forever()

Anyway, thought this might be useful. The solution will differ slightly in Python 3.0

无论如何,认为这可能有用。解决方案在 Python 3.0 中会略有不同