SocketServer.ThreadingTCPServer - No se puede enlazar a tratar después de reiniciar el programa
Pregunta
Como seguimiento a can not-bind-a-dirección -después-socket-programa-choques , que estaba recibiendo este error después se reinició mi programa:
socket.error: [Errno 98] Dirección ya en uso
En este caso particular, en lugar de utilizar directamente un socket, el programa está comenzando su propio servidor TCP roscado:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
¿Cómo puedo solucionar este mensaje de error?
Solución 2
En este caso particular, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
pueden ser llamados de la clase TCPServer cuando la opción se establece allow_reuse_address
. Así que yo era capaz de resolverlo de la siguiente manera:
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()
De todos modos, pensamos que podría ser útil. La solución diferirá ligeramente en Python 3.0
Otros consejos
La solución anterior no funcionó para mí, pero éste lo hizo:
SocketServer.ThreadingTCPServer.allow_reuse_address = True
server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
server.serve_forever()