SocketServer.ThreadingTCPServer - Cannot bind to address after program restart

蓝咒 提交于 2019-11-28 11:08:49

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()

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!