HTTPSimpleServer - 如何关闭/终止它?

1 投票
2 回答
1210 浏览
提问于 2025-04-16 23:30

我最近了解到,我可以用这个命令来启动一个服务器:

sudo python -m HTTPSimpleServer

我想问的是:当我用完这个服务器后,怎么把它关闭呢?

2 个回答

0

你可能想看看这个 servlet 模块里的 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
5

按下控制键和C键,简单就是这样。

撰写回答