0

I wrote my two classes

class RequestHandler(http.server.SimpleHTTPRequestHandler):

class Server(socketserver.TCPServer):

so that an unique Server can handle regular browser-, ajax- and websocket requests. It works fine.

I just can't find the way to terminate the Server. So I kill the process.

[EDIT] I need to shutdown the server when it receives a shutdown request from the browser. I tried setting self.__shutdown_request True but it didn't work.

Beside, after I have closed the browser and killed the process, netstat tells me there are some sockets still alive using the Server's port, with TIME_WAIT status. So I have to wait for them to die before to use the same port again.

How do I terminate the Server?

Is there a way to remove those sockets?

donkeydown
  • 698
  • 7
  • 16
  • Can't help you with the first issue, but to avoid sockets hanging around in TIME_WAIT state you can set SO_LINGER ON with a timeout of 0, as shown here http://stackoverflow.com/questions/6439790/sending-a-reset-in-tcp-ip-socket-connection – fvu Oct 15 '13 at 10:27

2 Answers2

3

May be you can try the method Server.shutdown to shutdown the server. As explained by the Python docs, this method tell the Server.serve_forever loop to stop and wait until it does. By the way, although you can set SO_LINGER ON to avoid the TIME_WAIT state of your TCP sockets, it is not encouraged to do so. An alternative is to set the SO_REUSEADDR before you bind the server port.

zhujs
  • 543
  • 2
  • 12
0

Use the following command in a terminal window to kill the TCP port 28355 to stop the TIME_WAIT socket:

npx kill-port 28355

In my python socket server script I used the following lines:

import os os.system("npx kill-port 28355")

This command solves the "Address already in use" error. It was the only solution that solved the error out of all the other solutions I found, like enabling the SO_REUSEADDR option.

ChristianYami
  • 586
  • 1
  • 9
  • 17