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

发布于 2024-08-21 22:43:31 字数 454 浏览 5 评论 0原文

作为 cannot-bind-to-address-after- 的后续操作socket-program-crashes,我的程序重新启动后收到此错误:

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

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

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

如何修复此错误消息?

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

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()

How can I fix this error message?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倒数 2024-08-28 22:43:31

上述解决方案对我不起作用,但这个解决方案却有效:

   SocketServer.ThreadingTCPServer.allow_reuse_address = True
   server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
   server.serve_forever()

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()
月野兔 2024-08-28 22:43:31

在这种特殊情况下,当设置 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 中的解决方案略有不同

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()

Anyway, thought this might be useful. The solution will differ slightly in Python 3.0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文