Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

show me how to build a simple web server from scratch in python, don't use libraries,…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219’s answer.
  1. User

    show me how to build a simple web server from scratch in python, don't use libraries, bare metal as much as possible

  2. Gemini Assistant

    You want to build a web server from scratch in Python, using as few pre-built abstractions as possible. This means we'll primarily rely on Python's built-in socket module, which provides the raw interface to network communication. We'll manually handle the HTTP protocol.

    What we'll build:

    1. A server that listens on a specified port.
    2. Accepts incoming client connections.
    3. Reads the raw HTTP request from the client.
    4. Parses the request line (e.g., GET / HTTP/1.1).
    5. Constructs a very basic HTTP response (status line, headers, and a simple HTML body).
    6. Sends the response back to the client.
    7. Closes the connection.

    Key Concepts (Bare Metal):

    • Socket: The endpoint for network communication. We'll create a TCP socket.
    • Bind: Associate the socket with a specific IP address and port number on the server machine.
    • Listen: Put the socket into listening mode, waiting for incoming connections.
    • Accept: A blocking call that waits for a client to connect. When a connection comes in, it returns a new socket specific to that client connection.
    • Recv: Read data from a socket.
    • Sendall: Send data to a socket.
    • HTTP Protocol: The rules for how web clients and servers communicate. We'll implement the bare minimum:
      • Request Line: METHOD PATH HTTP/VERSION (e.g., GET /index.html HTTP/1.1)
      • Headers: Key: Value pairs.
      • Blank Line: Separates headers from the body.
      • Response Line: HTTP/VERSION STATUS_CODE STATUS_TEXT (e.g., HTTP/1.1 200 OK)
      • Headers: Content-Type, Content-Length are essential for simple responses.

    The Bare-Metal Python Web Server Code

    import socket
    
    # --- Configuration ---
    HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
    PORT = 8080         # Port to listen on (non-privileged ports are > 1023)
    
    # --- HTTP Response Constants ---
    HTTP_200_OK = b"HTTP/1.1 200 OK\r\n"
    HTTP_404_NOT_FOUND = b"HTTP/1.1 404 Not Found\r\n"
    CONTENT_TYPE_HTML = b"Content-Type: text/html; charset=utf-8\r\n"
    
    # --- Simple HTML Content ---
    HTML_INDEX = b"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bare-Metal Server</title>
        <style>
            body { font-family: sans-serif; text-align: center; margin-top: 50px; background-color: #f0f0f0; }
            h1 { color: #333; }
            p { color: #666; }
        </style>
    </head>
    <body>
        <h1>Hello from your Bare-Metal Python Server!</h1>
        <p>You requested the root path (<code>/</code>).</p>
        <p>Try <a href="/about">/about</a> or <a href="/nonexistent">/nonexistent</a> to see the 404 page.</p>
    </body>
    </html>
    """
    
    HTML_ABOUT = b"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>About Us</title>
        <style>
            body { font-family: sans-serif; text-align: center; margin-top: 50px; background-color: #f0f0f0; }
            h1 { color: #333; }
            p { color: #666; }
        </style>
    </head>
    <body>
        <h1>About This Server</h1>
        <p>This is a very simple web server built from scratch in Python.</p>
        <p>It uses only the <code>socket</code> module and manually constructs HTTP responses.</p>
        <p><a href="/">Go back to home</a></p>
    </body>
    </html>
    """
    
    HTML_404 = b"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>404 Not Found</title>
        <style>
            body { font-family: sans-serif; text-align: center; margin-top: 50px; background-color: #f0f0f0; }
            h1 { color: #cc0000; }
            p { color: #666; }
        </style>
    </head>
    <body>
        <h1>404 Not Found</h1>
        <p>Sorry, the page you requested could not be found.</p>
        <p><a href="/">Go back to home</a></p>
    </body>
    </html>
    """
    
    def handle_request(client_socket):
        """
        Handles a single incoming client request.
        """
        try:
            # 1. Receive the request data (up to 1024 bytes)
            # We decode it from bytes to string for easier parsing.
            request_data_bytes = client_socket.recv(1024)
            if not request_data_bytes:
                print("Client closed connection before sending data.")
                return
    
            request_data_str = request_data_bytes.decode('utf-8')
    
            print(f"\n--- Received Request ---\n{request_data_str.strip()}\n------------------------")
    
            # 2. Parse the request line
            # The request line is the first line of the HTTP request.
            # Example: GET / HTTP/1.1
            request_lines = request_data_str.split('\r\n')
            request_line = request_lines[0]
    
            # Split the request line into parts (Method, Path, HTTP Version)
            parts = request_line.split(' ')
    
            if len(parts) < 2:
                print(f"Malformed request line: {request_line}")
                send_error_response(client_socket, 400, b"Bad Request")
                return
    
            method = parts[0]
            path = parts[1]
    
            print(f"Parsed: Method='{method}', Path='{path}'")
    
            # 3. Construct the response based on the path
            body_content = b""
            status_line = b""
            content_length = 0
    
            if path == '/':
                status_line = HTTP_200_OK
                body_content = HTML_INDEX
            elif path == '/about':
                status_line = HTTP_200_OK
                body_content = HTML_ABOUT
            else:
                status_line = HTTP_404_NOT_FOUND
                body_content = HTML_404
    
            content_length = len(body_content)
            content_length_header = f"Content-Length: {content_length}\r\n".encode('utf-8')
    
            # Construct the full HTTP response
            # HTTP response format:
            # Status-Line\r\n
            # Header: Value\r\n
            # Header: Value\r\n
            # \r\n (empty line separates headers from body)
            # Body
            response = (
                status_line +
                CONTENT_TYPE_HTML +
                content_length_header +
                b"\r\n" +  # Important: empty line separates headers from body
                body_content
            )
    
            # 4. Send the response back to the client
            client_socket.sendall(response)
            print("Response sent.")
    
        except Exception as e:
            print(f"Error handling request: {e}")
            send_error_response(client_socket, 500, b"Internal Server Error")
        finally:
            # 5. Close the client socket
            client_socket.close()
            print("Client connection closed.")
    
    def send_error_response(client_socket, status_code, status_text):
        """Sends a generic error response."""
        error_html = f"<html><body><h1>{status_code} {status_text.decode()}</h1><p>An error occurred.</p></body></html>".encode('utf-8')
        response_line = f"HTTP/1.1 {status_code} {status_text.decode()}\r\n".encode('utf-8')
        content_length_header = f"Content-Length: {len(error_html)}\r\n".encode('utf-8')
    
        response = (
            response_line +
            CONTENT_TYPE_HTML +
            content_length_header +
            b"\r\n" +
            error_html
        )
        try:
            client_socket.sendall(response)
        except Exception as e:
            print(f"Error sending error response: {e}")
    
    
    def run_server():
        """
        Sets up and runs the main server loop.
        """
        # Create a socket object
        # AF_INET: specifies the address family (IPv4)
        # SOCK_STREAM: specifies the socket type (TCP)
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        # Allow the server to reuse the address immediately after closing,
        # preventing "Address already in use" errors if you restart quickly.
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    
        try:
            # Bind the socket to the host and port
            server_socket.bind((HOST, PORT))
            print(f"Server bound to {HOST}:{PORT}")
    
            # Listen for incoming connections
            # The argument (5) specifies the maximum number of queued connections
            server_socket.listen(5)
            print("Server is listening for connections...")
    
            while True:
                # Accept a new connection
                # This is a blocking call; it waits until a client connects.
                # Returns a new socket object representing the connection
                # and a tuple holding the address of the client.
                client_socket, client_address = server_socket.accept()
                print(f"\nAccepted connection from {client_address}")
    
                # Handle the client request
                # For simplicity, this server handles one request at a time (synchronously).
                # For a production server, you'd typically use threading or asyncio here.
                handle_request(client_socket)
    
        except KeyboardInterrupt:
            print("\nServer shutting down.")
        except Exception as e:
            print(f"An unexpected server error occurred: {e}")
        finally:
            # Ensure the server socket is closed when the script exits
            server_socket.close()
            print("Server socket closed.")
    
    if __name__ == '__main__':
        run_server()
    

    How to Run and Test:

    1. Save the code: Save the code above as simple_server.py.
    2. Open your terminal/command prompt: Navigate to the directory where you saved the file.
    3. Run the server:
      python simple_server.py
      
      You should see output like:
      Server bound to 127.0.0.1:8080
      Server is listening for connections...
      
    4. Open your web browser:
      • Go to http://localhost:8080/
      • You should see the "Hello from your Bare-Metal Python Server!" message.
      • Try http://localhost:8080/about
      • Try http://localhost:8080/something_else (this should show the 404 page).
    5. Check the terminal: Observe the output in your terminal. You'll see the raw HTTP request received from your browser and the server's actions.
    6. Stop the server: Press Ctrl+C in the terminal where the server is running.

    Limitations and Next Steps (if you were to build a real server):

    This server is extremely basic and has many limitations:

    1. Synchronous (one request at a time): It handles one client connection completely before accepting the next. For concurrent requests (which all web servers need), you'd use:
      • Threading: Start a new thread for each client connection (threading module).
      • Asynchronous I/O: Use asyncio to manage multiple connections without blocking.
      • Forking: Create a new process for each client (common on Unix-like systems).
    2. Basic Request Parsing: It only extracts the method and path. Real servers parse all headers, query parameters, cookies, request body (for POST/PUT), etc.
    3. No Error Handling for Partial Reads: client_socket.recv(1024) assumes the entire request fits within 1024 bytes and arrives in one go. Real servers loop recv until the entire request (identified by \r\n\r\n or Content-Length) is received.
    4. No Static File Serving: It only serves hardcoded HTML strings. A real server would read files from disk (e.g., index.html, style.css, images).
    5. No Routing/Framework: The if path == '/' logic is hardcoded. Web frameworks (like Flask, Django) provide robust routing mechanisms.
    6. No SSL/TLS (HTTPS): All communication is unencrypted.
    7. Limited HTTP Methods: Only implicitly handles GET.
    8. No persistent connections: It closes the connection after each request. Real servers often support Connection: keep-alive.

    This example truly demonstrates the "bare metal" aspects of a web server. Any practical web server framework (even a micro-framework like Flask) sits on top of these fundamental socket operations, abstracting away the complexities of HTTP parsing, routing, concurrency, and error handling.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.