Tutorialspoint
Problem
Solution
Submissions

Multi-threaded Web Server

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program to implement a multi-threaded web server that can handle multiple client requests concurrently. The server should be able to serve static files from a specified directory and handle basic HTTP requests.

Example 1
  • Input:
    server = WebServer(port=8080, document_root="./www")
    server.start()
    # Client: GET /index.html HTTP/1.1
  • Output:
    HTTP/1.1 200 OK
    Content-Type: text/html
    Content-Length: 325
    ...<html><head><title>Welcome</title></head><body><h1>Hello World!</h1></body></html>
  • Explanation:
    • Server returns index.html from document root.
    • Includes correct HTTP headers.
Example 2
  • Input:
    # Client: GET /nonexistent.html HTTP/1.1
  • Output:
    HTTP/1.1 404 Not Found
    ...<h1>404 Not Found</h1><p>The requested resource was not found.</p>
  • Explanation:
    • 404 error page returned for missing file.
Constraints
  • ≥ 50 concurrent connections
  • Max static file size: 100MB
  • Response time ≤ 500ms
  • Supports .html, .css, .js, .jpg, .png, .gif
  • Time Complexity: O(n)
  • Space Complexity: O(m)
File Handling Multi-Threading AmazonGoogle
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Python's socket module to create a TCP server
  • Implement threading with Python's threading module
  • Create a thread pool to limit and manage concurrent connections
  • Parse HTTP requests and generate appropriate HTTP responses
  • Use file I/O operations to read static files from the document root

Steps to solve by this approach:

 Step 1: Set up a socket server that listens on the specified port.
 Step 2: Create a main server loop that accepts client connections.
 Step 3: Implement multi-threading to handle each client connection in a separate thread.
 Step 4: Parse incoming HTTP requests to extract the method, path, and headers.
 Step 5: Generate appropriate HTTP responses based on the request and file system.
 Step 6: Add error handling for invalid requests and missing resources.
 Step 7: Implement proper resource cleanup for sockets and threads.

Submitted Code :