13

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

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

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

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

如何修复此错误消息?

4

2 回答 2

18

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

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
   server.serve_forever()
于 2010-06-29T04:09:00.050 回答
16

在这种特殊情况下,.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()

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

于 2010-02-16T16:17:02.727 回答