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

Jus*_*ier 10 python sockets linux tcpserver

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

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

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

httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

我该如何修复此错误消息?

Lyn*_*ynn 16

上面的解决方案对我没有用,但是这个解决了:

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
   server.serve_forever()
Run Code Online (Sandbox Code Playgroud)


Jus*_*ier 11

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

无论如何,认为这可能是有用的.Python 3.0中的解决方案略有不同