Python Network Programming HTTP Server

Python Network Programming HTTP Server

The Python standard library has a built-in network server that can be called for simple network client-server communication. A port number can be specified programmatically, and the network server can be accessed through that port. While it’s not a full-featured network server capable of parsing a variety of files, it can parse simple static HTML files and serve them by responding with the required response code.

The following program starts a simple network server and opens it on port 8001. As shown in the program output, successful server operation is indicated by a 200 response code.

import SimpleHTTPServer
import SocketServer

PORT = 8001

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

When we run the above program, we get the following output −

serving at port 8001
127.0.0.1 - - [14/Jun/2018 08:34:22] "GET / HTTP/1.1" 200 -

Serving localhost

If we decide to use the Python server as a local host, serving only the local host, we can use the following program to achieve this.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"

if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

When we run the above program, we get the following output −

Serving HTTP on 127.0.0.1 port 8000 ...

Leave a Reply

Your email address will not be published. Required fields are marked *