[Tutor] Closing SimpleXMLRPCServer properly

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Aug 31 21:21:55 CEST 2005

> class StoppableXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
> def serve_forever(self):
> """to stop this server: register a function in the class
> that uses it which sets server.stop to True."""
> self.stop = False
> while not self.stop:
> self.handle_request()
> Here's the code where I start the server...
> try:
> self.server.serve_forever()
> finally:
> self.server.server_close()
> self.log('server closed')
> >From another thread, I set the server's stop attribute to False, so the
> server stops running. It exits the try block, runs server_close(), then I
> get the message 'server closed'...
> ...but when I try to use the port that the server's bound to again, it
> takes a very long time (while i try to use the port, catch the
> exception, sleep, try again) until it becomes free. Is there something
> else I need to call to ensure that the port is released cleanly? Is this
> an OS-specific thing out of my control? (I'm running Debian Linux.)

Hi Lawrence,

It's TCP specific.  When the server shuts down, the port is in a TIME_WAIT
state that causes the port to wait until things are cleanly shut down.

For more information on TIME_WAIT, see:


Anyway, you can force the issue, get the server to "reuse" the address, by
setting the "allow_reuse_address" attribute on your server.

class StoppableXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
    """Override of TIME_WAIT"""
    allow_reuse_address = True

    def serve_forever(self):
        self.stop = False
        while not self.stop:



for a brief mention of allow_reuse_address.

One of these days, I have to read Richard Stevens's book on TCP to better
understand what exactly is going on.  I have to admit that I don't
understand the TCP model quite well yet.

Best of wishes to you!

More information about the Tutor mailing list