Building a custom, lightweight HTTP server from scratch—often playfully called a “CoffeeWebServer”—is an excellent way to learn networking basics. It involves opening network sockets, listening for incoming connections, and parsing raw text strings into HTTP requests.
Here is how you can build a minimalist, single-threaded web server using Python. Core Concepts An HTTP server relies on three fundamental mechanisms:
Sockets: The doorways that let your program send and receive data over the network.
TCP/IP: The underlying protocol ensuring your data arrives reliably and in the correct order.
HTTP Protocol: A plain-text messaging standard where clients send requests and servers return responses. Complete Python Implementation
Save the following code as server.py. It uses Python’s built-in socket library, requiring no external dependencies.
import socket def start_server(): # Define host and port HOST = ‘127.0.0.1’ PORT = 8080 # 1. Create a TCP socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 2. Bind the socket to the address and port server_socket.bind((HOST, PORT)) # 3. Listen for incoming connections (queue up to 5 requests) server_socket.listen(5) print(f”☕ CoffeeWebServer running on http://{HOST}:{PORT}…“) while True: # 4. Accept a client connection client_connection, client_address = server_socket.accept() # 5. Receive the raw HTTP request data request_data = client_connection.recv(1024).decode(‘utf-8’) if not request_data: client_connection.close() continue print(f” — Received Request From {client_address} —“) print(request_data.splitlines()[0]) # Prints just the request line # 6. Construct a plain-text HTTP response http_response = ( “HTTP/1.1 200 OK” “Content-Type: text/html; charset=utf-8 ” “Connection: close ” “
☕ Welcome to CoffeeWebServer
” “
Your fresh brew of data is ready.
” ) # 7. Send the response and close the connection client_connection.sendall(http_response.encode(‘utf-8’)) client_connection.close() if name == “main”: start_server() Use code with caution. How to Run and Test It Run the script from your terminal: python server.py Open your web browser and navigate to http://127.0.0.1:8080
The page will display your HTML, and the terminal will log the incoming browser request. Behind the Scenes: The HTTP Conversation
When your browser connects, it sends a text block that looks like this:
Leave a Reply