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

作为无法绑定到地址后套接字程序崩溃的后续行动,我的程序重新启动后,我收到了这个错误:

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

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

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

我怎样才能解决这个错误信息?

上面的解决方案不适合我,但这个做了:

  Socketserver.ThreadingTCPserver.allow_reuse_address = True server = Socketserver.ThreadingTCPserver(("localhost", port), CustomHandler) server.serve_forever() 

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

 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中的解决方案略有不同