简体   繁体   English

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

[英]SocketServer.ThreadingTCPServer - Cannot bind to address after program restart

As a follow-up to cannot-bind-to-address-after-socket-program-crashes , I was receiving this error after my program was restarted: 作为无法绑定到地址后套接字程序崩溃的后续操作,我在重新启动程序后收到此错误:

socket.error: [Errno 98] Address already in use socket.error:[Errno 98]地址已被使用

In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server: 在这种特殊情况下,程序不是直接使用套接字,而是启动自己的线程TCP服务器:

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

How can I fix this error message? 我该如何修复此错误消息?

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. 在这种特殊情况下,当设置allow_reuse_address选项时,可以从TCPServer类调用.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 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 Python 3.0中的解决方案略有不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM