SocketServer.ThreadingTCPServer - 程序重新启动后无法绑定地址

13
作为对 cannot-bind-to-address-after-socket-program-crashes 的跟进,我在程序重新启动后收到了这个错误信息:

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

在这种特殊情况下,程序不是直接使用套接字,而是启动了自己的线程化TCP服务器。
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()

我该如何修复这个错误信息?

2个回答

20

以上解决方案对我无效,但这个解决方案可行:

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

有趣,你使用的是哪个版本的Python? - Justin Ethier
这里也一样,这个可以工作但是不适用于httpd.server_bind()。Python 2.6.5。 - rombarcz
在Python 3.4.3上对我有效,但Justin的答案无效。 - Oliver Bock
根据文档,这不被推荐,推荐的方法是子类化。 - undefined

16

在这种特殊情况下,当设置allow_reuse_address选项时,.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)可能会从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()

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接