Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SocketServer

How can I call shutdown() in a SocketServer after receiving a certain message "exit"? As I know, the call to serve_forever() will block the server.

Thanks!

like image 778
carlosalbertomst Avatar asked Oct 05 '10 11:10

carlosalbertomst


People also ask

What is Socketserver in Python?

Source code: Lib/socketserver.py. The socketserver module simplifies the task of writing network servers. There are four basic concrete server classes: class socketserver.

What is a Socketserver class?

The SocketServer module is a framework for creating network servers. It defines classes for handling synchronous network requests (the server request handler blocks until the request is completed) over TCP, UDP, Unix streams, and Unix datagrams.

What is a socket server?

Sockets are commonly used for client and server interaction. Typical system configuration places the server on one machine, with the clients on other machines. The clients connect to the server, exchange information, and then disconnect. A socket has a typical flow of events.


2 Answers

Use the source, Luke!

Excerpt from SocketServer.py:

   def serve_forever(self, poll_interval=0.5):
        """Handle one request at a time until shutdown.

        Polls for shutdown every poll_interval seconds. Ignores
        self.timeout. If you need to do periodic tasks, do them in
        another thread.
        """
        self.__is_shut_down.clear()
        try:
            while not self.__shutdown_request:
                # XXX: Consider using another file descriptor or
                # connecting to the socket to wake this up instead of
                # polling. Polling reduces our responsiveness to a
                # shutdown request and wastes cpu at all other times.
                r, w, e = select.select([self], [], [], poll_interval)
                if self in r:
                    self._handle_request_noblock()
        finally:
            self.__shutdown_request = False
            self.__is_shut_down.set()

    def shutdown(self):
        """Stops the serve_forever loop.

        Blocks until the loop has finished. This must be called while
        serve_forever() is running in another thread, or it will
        deadlock.
        """
        self.__shutdown_request = True
        self.__is_shut_down.wait()
like image 94
Mark Tolonen Avatar answered Nov 12 '22 05:11

Mark Tolonen


No the serve_forever is checking a flag on a regular basis (by default 0.5 sec). Calling shutdown will raise this flag and cause the serve_forever to end.

like image 37
luc Avatar answered Nov 12 '22 04:11

luc