HTTPSimpleServer - Как закрыть / прекратить его? - PullRequest
1 голос
/ 12 августа 2011

Я недавно узнал, что могу запустить сервер с помощью этой команды:

sudo python -m HTTPSimpleServer

Мой вопрос: как мне завершить работу этого сервера?

Ответы [ 2 ]

5 голосов
/ 12 августа 2011

Тип управления-C. Все просто.

0 голосов
/ 12 августа 2011

Возможно, вы захотите проверить класс HttpServer в этом модуле сервлета на наличие модификации, позволяющей завершить работу сервера.Если обработчик вызывает исключение SystemExit, сервер перестает обслуживать.


class HttpServer(socketserver.ThreadingMixIn, http.server.HTTPServer):

    """Create a server with specified address and handler.

    A generic web server can be instantiated with this class. It will listen
    on the address given to its constructor and will use the handler class
    to process all incoming traffic. Running a server is greatly simplified."""

    # We should not be binding to an
    # address that is already in use.
    allow_reuse_address = False

    @classmethod
    def main(cls, RequestHandlerClass, port=80):
        """Start server with handler on given port.

        This static method provides an easy way to start, run, and exit
        a HttpServer instance. The server will be executed if possible,
        and the computer's web browser will be directed to the address."""
        try:
            server = cls(('', port), RequestHandlerClass)
            active = True
        except socket.error:
            active = False
        else:
            addr, port = server.socket.getsockname()
            print('Serving HTTP on', addr, 'port', port, '...')
        finally:
            port = '' if port == 80 else ':' + str(port)
            addr = 'http://localhost' + port + '/'
            webbrowser.open(addr)
        if active:
            try:
                server.serve_forever()
            except KeyboardInterrupt:
                print('Keyboard interrupt received: EXITING')
            finally:
                server.server_close()

    def handle_error(self, request, client_address):
        """Process exceptions raised by the RequestHandlerClass.

        Overriding this method is necessary for two different reasons:
        (1) SystemExit exceptions are incorrectly caught otherwise and
        (2) Socket errors should be silently passed in the server code"""
        klass, value = sys.exc_info()[:2]
        if klass is SystemExit:
            self.__exit = value
            self._BaseServer__serving = None
        elif issubclass(klass, socket.error):
            pass
        else:
            super().handle_error(request, client_address)

    def serve_forever(self, poll_interval=0.5):
        """Handle all incoming client requests forever.

        This method has been overridden so that SystemExit exceptions
        raised in the RequestHandlerClass can be re-raised after being
        caught in the handle_error method above. This allows servlet
        code to terminate server execution if so desired or required."""
        super().serve_forever(poll_interval)
        if self._BaseServer__serving is None:
            raise self.__exit
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...