SocketServer.ThreadingTCPServer - Impossibile associare ad affrontare dopo il riavvio del programma
Domanda
Come follow-up a can not-bind-to-address -Dopo-socket-programma-crash , stavo ricevendo questo errore dopo il mio programma è stato riavviato:
socket.error: [Errno 98] Indirizzo già in uso
In questo caso particolare, invece di utilizzare direttamente una presa, il programma sta iniziando proprio server TCP filettato:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
Come posso risolvere questo messaggio di errore?
Soluzione 2
In questo caso particolare, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
possono essere chiamati dalla classe TCPServer quando l'opzione allow_reuse_address
è impostata. Così mi è stato in grado di risolverlo nel seguente modo:
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()
In ogni caso, pensato che questo potrebbe essere utile. La soluzione sarà leggermente diverso in Python 3.0
Altri suggerimenti
La soluzione di cui sopra non ha funzionato per me, ma questo fatto:
SocketServer.ThreadingTCPServer.allow_reuse_address = True
server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
server.serve_forever()