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

13 投票
2 回答
14011 浏览
提问于 2025-04-15 19:21

这是对一个问题的后续讨论,之前的问题是关于“程序崩溃后无法绑定地址”。我在重新启动我的程序时收到了这个错误信息:

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

在这个特定的情况下,程序并不是直接使用一个套接字,而是启动了自己的多线程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()
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 中会稍有不同。

撰写回答