Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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() 
like image 781
JW. Avatar asked Sep 13 '08 16:09

JW.


People also ask

How does HTTP server work in Python?

HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. <p>Congratulations! The HTTP Server is working!

What is simple HTTP server in Python?

The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. The module loads and serves any files within the directory on port 8000 by default.


1 Answers

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):     daemon_threads = True  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) 

update:

This also works with Python 3 but three lines need to be slightly changed:

from socketserver import ThreadingMixIn from http.server import HTTPServer, BaseHTTPRequestHandler 

and

self.wfile.write(bytes("Hello World!", "utf-8")) 
like image 98
Eli Courtwright Avatar answered Oct 06 '22 08:10

Eli Courtwright