Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Network Programming Python – HTTP Server

  • Last Updated : 24 Oct, 2020

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.

Python has a built-in webserver provided by its standard library, can be called for simple client-server communication. The http.server and socketserver are the two main functions used to create a web server. Port number can be defined manually in the program which is used to access the webserver. This web server is functional for many types of file formats, but it is not fully featured. A simple static HTML files can easily be parsed and served by responding with the required response code. A basic implementation of python HTTP web server is given below :

Sample HTML File :



       <title>Python HTTP Server</title>



       <h1>Simple HTTP Server</h1>

       <p>Congratulations! The HTTP Server is working!

Welcome to GeeksForGeeks</p>




# Import libraries
import http.server
import socketserver
# Defining PORT number
PORT = 8080
# Creating handle
Handler = http.server.SimpleHTTPRequestHandler
# Creating TCPServer
http = socketserver.TCPServer(("", PORT), Handler)
# Getting logs
print("serving at port", PORT)


serving at port 8080 - - [17/Oct/2020 00:31:27] "GET / HTTP/1.1" 200 -

Execute the above program in the directory where the HTML File is saved. After creating the Web Server open the Web Browser and type http://localhost:8080/ in the URL. 

Here, SimpleHTTPRequestHandler is used to create a custom handler. TCPServer tells the server to send and receive messages. To invoke TCPServer, two arguments are required the TCP Address i.e. IP and PORT, and second is the handler. TCP Address is a tuple consisting of IP address and PORT number. Serve_forever() is a function of the TCPServer instance that starts the server and listens and responds to the incoming requests.

The localhost is the host machine(in our case the system we are using), used to access the network services using the loopback network interface.

If the python program is to be used only as localhost serving, the below program is used for that purpose :


# Import libraries
import sys
import http.server
import socketserver
# Creating handle
HandlerClass = http.server.SimpleHTTPRequestHandler
# Creating Server
ServerClass  = http.server.HTTPServer
# Defining protocol
Protocol     = "HTTP/1.0"
# Setting TCP Address
if sys.argv[1:]:
    port = int(sys.argv[1])
    port = 8000
server_address = ('', port)
# invoking server
HandlerClass.protocol_version = Protocol
http = ServerClass(server_address, HandlerClass)
# Getting logs
sa = http.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!