python socket server address already in use

1.5k views Asked by At

Hi I'm trying use python's SocketServer.TCPServer The question here doesn't give any solution and closed as unclear

My sample code

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # self.request is the TCP socket connected to the client         
        self.data = self.request.recv(1024).strip()                      
        print "{} wrote:".format(self.client_address[0])                 
        print self.data                                                  
        time.sleep(5)                                                    
        # just send back the same data, but upper-cased                  
        self.request.sendall(self.data.upper())                          
        print 'done handing request from {0}'.format(self.client_address[0])

if __name__ == '__main':
    HOST = socket.gethostname()
    PORT = int(sys.argv[1])
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

Problem is when restart the server it says

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

Looked at what server.shutdown() is doing in SocketServer.TCPServer.

It is not closing any socket, so I have tried running this in a different thread an handling the shutdown of the server by calling

server.shutdown()
server.server_close()

Tried changing the order of the calls to shutdown() and server_close()

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

I used curl command to test.

Using netstat I can see that the port is in TIME_WAIT state

0

There are 0 answers