How do I write a python HTTP server to listen on multiple ports?

后端 未结 3 1476
忘掉有多难
忘掉有多难 2020-12-07 23:37

I\'m writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more th

3条回答
  •  醉梦人生
    2020-12-08 00:06

    Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).

    The existing function:

    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.__serving = True
        self.__is_shut_down.clear()
        while self.__serving:
            # 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 r:
                self._handle_request_noblock()
        self.__is_shut_down.set()
    

    So our replacement would be something like:

    def serve_forever(server1,server2):
        while True:
            r,w,e = select.select([server1,server2],[],[],0)
            if server1 in r:
                server1.handle_request()
            if server2 in r:
                server2.handle_request()
    

提交回复
热议问题