代码之家  ›  专栏  ›  技术社区  ›  Justin Ethier

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

  •  10
  • Justin Ethier  · 技术社区  · 15 年前

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

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

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

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

    如何修复此错误消息?

    2 回复  |  直到 11 年前
        1
  •  16
  •   Lynn    14 年前

       SocketServer.ThreadingTCPServer.allow_reuse_address = True
       server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
       server.serve_forever()
    
        2
  •  11
  •   Justin Ethier    15 年前

    .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) allow_reuse_address

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