How to kill a SocketServer?

Skip Montanaro skip at pobox.com
Mon May 2 12:22:33 EDT 2005


    >> > set self.pause to something short-ish.  The select call times out
    >> > and the server exits.

    Guido> [Paul Rubin]
    >> Ah, good point.  Something like this should probably be added to
    >> SocketServer.py (optional timeout parameter to serve_forever), or at
    >> least the trick should be mentioned in the docs.

    Guido> I like this idea, and perhaps you all could come up with some
    Guido> more useful APIs in this area...

I stumbled on a somewhat cleaner way to do this using socket timeouts:

    class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
        pause = 0.25
        allow_reuse_address = True

        def __init__(self, server_address, RequestHandlerClass):
            SocketServer.TCPServer.__init__(self, server_address,
                                            RequestHandlerClass)
            self.socket.settimeout(self.pause)
            self.serving = 1
            ...

        def serve_forever(self):
            while self.serving:
                self.handle_request()

As far as my simple testing went (a trivial little xmlrpc server exposing
only "noop" and "exit" methods), the above worked fine.  I was mildly
surprised that I didn't have to catch socket.timeout exceptions.

Skip




More information about the Python-list mailing list