How to kill a SocketServer?

Skip Montanaro skip at pobox.com
Sun May 1 14:32:24 EDT 2005


    Paul> Let's say you have a SocketServer with the threading mix-in and
    Paul> you run serve_forever on it.  How can you shut it down, or rather,
    Paul> how can it even shut itself down?  Even if you use a
    Paul> handle_request loop instead of serve_forever, it still seems
    Paul> difficult:

    Paul>      class myserver(ThreadingMixIn, TCPServer): pass
    Paul>      server = myserver(...)
    Paul>      server.shutdown = False
    Paul>      while not server.shutdown:
    Paul>          server.handle_request()

    Paul> Some code in the request handler eventually sets server.shutdown
    Paul> to True (say on receiving a "shutdown" command from the client),
    Paul> but by then the main thread is already blocked waiting for another
    Paul> connection.

I use precisely that scheme with (I think *) no problem.  The only maybe
significant difference I see is that I subclass ThreadingMixin so that it
creates daemon threads:

    class DaemonThreadMixIn(SocketServer.ThreadingMixIn):
        def process_request_thread(self, request, client_address):
            try:
                self.finish_request(request, client_address)
                self.close_request(request)
            except:
                self.handle_error(request, client_address)
                self.close_request(request)

        def process_request(self, request, client_address):
            t = threading.Thread(target = self.process_request_thread,
                                 args = (request, client_address))
            t.setDaemon(1)
            t.start()

    class GenericServer(DaemonThreadMixIn, SocketServer.TCPServer):
        ...

Skip

(*) Maybe my XML-RPC server actually accepts one more connection after I set
server.shutdown to True before it actually exits.  I'll have to take a look
at that.



More information about the Python-list mailing list