SocketServer.ThreadingTCPServer-程序重新启动后无法绑定到地址 [英] SocketServer.ThreadingTCPServer - Cannot bind to address after program restart
问题描述
作为无法绑定到地址的后续操作-after-socket-program-crashes ,我的程序重新启动后,我收到此错误:
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]地址已在使用中
socket.error: [Errno 98] Address already in use
在这种特殊情况下,程序将直接启动其自己的线程化TCP服务器,而不是直接使用套接字:
In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
如何解决此错误消息?
推荐答案
在这种特殊情况下,当设置allow_reuse_address
选项时,可以从TCPServer类中调用.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
.因此,我能够按以下方式解决它:
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()
无论如何,以为这可能有用.该解决方案在Python 3.0中会略有不同
Anyway, thought this might be useful. The solution will differ slightly in Python 3.0
这篇关于SocketServer.ThreadingTCPServer-程序重新启动后无法绑定到地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!