Implementing an http server in python

Implementing an http server in python

Importing the Socket Module

Python
import socket

Creating and Configuring the Server Socket

Python
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))

Listening for Incoming Connections

Python
mySocket.listen(5)

Handling Incoming Connections in a Loop

Python
while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()

Handling HTTP Request and Sending Response

Python
print('HTTP request received:')
print(recvSocket.recv(1024))
Python
recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))

Closing the Connection

Python
recvSocket.close()
Python
import socket

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))

mySocket.listen(5)

while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()
    print('HTTP request received:')
    print(recvSocket.recv(1024))
    recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))
    recvSocket.close()

This script represents a simple HTTP server that listens on localhost:8080. It accepts incoming connections, prints received HTTP requests, sends a basic HTML response, and then closes the connection. Note that this example is minimal and may not handle all aspects of a production-level HTTP server. It’s mainly intended for educational purposes.

Implementing a basic HTTP server in Python can be done using the built-in http.server module. Below is a simple example of how you can create an HTTP server that serves static files from the current directory.

Python
import http.server
import socketserver

# Set the port number
port = 8080

# Choose the handler you want to use
handler = http.server.SimpleHTTPRequestHandler

# Create the server with the specified handler
with socketserver.TCPServer(("", port), handler) as httpd:
    print(f"Serving on port {port}")
    # Start the server
    httpd.serve_forever()

Here’s a breakdown of the code:

  1. Import Necessary Modules:
    • http.server: Provides basic HTTP server classes.
    • socketserver: Allows the creation of network servers.
  2. Set the Port Number:
    • Define the port on which the server will listen. In this case, it’s set to 8080.
  3. Choose the Handler:
    • Use http.server.SimpleHTTPRequestHandler as the handler. This handler serves files from the current directory and its subdirectories.
  4. Create and Start the Server:
    • Use socketserver.TCPServer to create a TCP server, specifying the host (“” means all available interfaces) and the port.
    • The with statement ensures that the server is properly closed when the script exits.
    • Print a message indicating that the server is running.
    • Call httpd.serve_forever() to start serving requests indefinitely.

Save this code in a file (e.g., http_server.py) and run it using:

Bash
python http_server.py

Your basic HTTP server will be accessible at http://localhost:8080, and you can navigate to different files and directories within the current directory. This example is suitable for serving static files during development, and for production, you may consider more advanced frameworks like Flask or Django.

Testing the HTTP Server

Shebang and Importing the Socket Module

Python
#!/usr/bin/python
import socket

Setting Web Host and Port

Python
webhost = 'localhost'
webport = 8080

Connecting to the Web Server

Python
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))

Sending an HTTP GET Request

Python
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))

Receiving and Printing the Server’s Response

Python
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())

Closing the Socket

Python
webclient.close()
Python
#!/usr/bin/python
import socket
webhost = 'localhost'
webport = 8080
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())

This script acts as a simple HTTP client that connects to a web server (localhost:8080 in this case), sends an HTTP GET request, receives the server’s response, and prints it. Note that this example is minimal and may not handle all aspects of a production-level HTTP client. It’s mainly intended for educational purposes.

Exit mobile version