2010-02-16 13 views
10

Come un follow-up a cannot-bind-to-address-after-socket-program-crashes, stavo ricevendo questo errore dopo il mio programma è stato riavviato:SocketServer.ThreadingTCPServer - non può legarsi ad affrontare dopo il riavvio del programma

socket.error: [Errno 98] Address already in use

In questo caso particolare, invece di utilizzare un socket direttamente, il programma sta avviando il proprio server TCP filettato:

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

Come posso risolvere questo messaggio di errore?

risposta

11

In questo caso particolare, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) può essere chiamato dalla classe TCPServer quando è impostata l'opzione allow_reuse_address. Così mi è stato in grado di risolvere nel modo seguente:

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

+0

Questo ha funzionato per me, ma non quanto sopra! Grazie. –

16

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

Interessante, quale versione di Python stai usando? –

+0

2.6.1 in Mac OSX. – Lynn

+0

stesso, questo funziona ma non uno con httpd.server_bind() Python 2.6.5 – rombarcz

Problemi correlati