Search code examples
pythonsocketstcpserversocketserver

How to stop TCPServer


On every of three iterations TCPServer needs to be started and then immediately stopped. All three times it needs to be started on port 8000.

As it defined in a code below, the TCPServer starts. But it starts only during the first iteration. Two others iterations fail to start TCPServer because the port 8000 is already in use by the TCPServer started in a previous (first) iteration. To make sure the port 8000 is available the previously started TCP Server needs to be shutdown.

How to terminate (stop) already running TCPServer?

import SimpleHTTPServer
import SocketServer


def startServer():
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    Handler.extensions_map.update({'.webapp': 'application/x-web-app-manifest+json', })
    try:
        httpd = SocketServer.TCPServer(("", 8000), Handler)
        httpd.serve_forever()
        print('httpd server has been successfully started ')
    except Exception, e:
        print(e)


for i in range(3):
    startServer()

Solution

  • Use shutdown() Tell the serve_forever() loop to stop and wait until it does. New in version 2.6. docs.python.org/2/library/socketserver.html

    For your code it should be as simple as

        httpd.serve_forever()
        print('httpd server has been successfully started ')
        httpd.shutdown()
        httpd.server_close()
        print('httpd server has been successfully stopped')
    

    I will leave it to the OP to better use this and the example at the bottom of the linked page appropriatly for the desired requirment.