How do I write a python HTTP server to listen on multiple ports?
Question: 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 than one port?

What I'm doing now:

    
    
    class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
      def doGET
      [...]
    
    class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): 
        pass
    
    server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
    server.serve_forever()
    


Answer: Sure; just start two different servers on two different ports in two different
threads that each use the same handler. Here's a complete, working example
that I just wrote and tested. If you run this code then you'll be able to get
a Hello World webpage at both <http://localhost:1111/> and
<http://localhost:2222/>

    
    
    from threading import Thread
    from SocketServer import ThreadingMixIn
    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
    
    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write("Hello World!")
    
    class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
        pass
    
    def serve_on_port(port):
        server = ThreadingHTTPServer(("localhost",port), Handler)
        server.serve_forever()
    
    Thread(target=serve_on_port, args=[1111]).start()
    serve_on_port(2222)
    

