How to stop a SocketServer?

Peter Hansen peter at engcorp.com
Mon Jun 24 20:55:14 EDT 2002


Daniel Fackrell wrote:
> 
> "Peter Hansen" <peter at engcorp.com> wrote:
> 
> Any chance I could see a very simple example of this in action?  That would
> help my little project out quite a bit.

This is just pulled out of a little server somebody around here wrote
the other week.  Out of context it might not help, but maybe the idea
would give you a start.  By the way, look into "timeoutsocket.py"
which is a plug-in replacement for the standard socket.py and which
might do the trick for you.

    def run(self):
        import threading

        try:

            try:
                # handle requests, waking up often to check if we should terminate
                while not self.sockserver.terminated:
                    readySocket = select([self.sockserver.socket], [],
                        [self.sockserver.socket], SELECT_TIMEOUT)

                    if readySocket[0] or readySocket[2] :
                        if threading.activeCount() < self.threadLimit:
                            self.sockserver.handle_request()
                        else:
                            time.sleep(0.5)

            finally:
                self.sockserver.socket.close()

        except:
            if self.exceptionHandler:
                self.exceptionHandler.handle()

        return


> Would this be something that would allow me to guarantee that the all
> threads of the server terminated within, say, five seconds of the server
> shutdown request?

I believe it would allow you to guarantee that.

I also think Skip's suggestion in another thread is even better if you're
just trying to terminate the whole application.

-Peter



More information about the Python-list mailing list