threadsafe_http_server.py


SUBMITTED BY: okpalan86

DATE: April 17, 2024, 12:29 p.m.

FORMAT: Text only

SIZE: 1.6 kB

HITS: 85

  1. import threading
  2. from http.server import BaseHTTPRequestHandler, HTTPServer
  3. # Define the HTTP request handler class
  4. class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
  5. # Override the do_GET method to handle GET requests
  6. def do_GET(self):
  7. # Set the response status code
  8. self.send_response(200)
  9. # Set the response headers
  10. self.send_header('Content-type', 'text/html')
  11. self.end_headers()
  12. # Write the response content
  13. self.wfile.write(b"Hello, world!")
  14. # Define the HTTP server class
  15. class ThreadedHTTPServer(HTTPServer):
  16. # Override the process_request method to handle each request in a separate thread
  17. def process_request(self, request, client_address):
  18. # Create a new thread for each request
  19. t = threading.Thread(target=self.__new_request_thread, args=(request, client_address))
  20. # Start the thread
  21. t.start()
  22. # Method to handle each request in a separate thread
  23. def __new_request_thread(self, request, client_address):
  24. # Call the superclass's process_request method to handle the request
  25. super().process_request(request, client_address)
  26. # Main function to run the server
  27. def main():
  28. # Define the server address and port
  29. server_address = ('', 8000)
  30. # Create an instance of the threaded HTTP server
  31. httpd = ThreadedHTTPServer(server_address, SimpleHTTPRequestHandler)
  32. print("Server started on port 8000...")
  33. # Start serving HTTP requests
  34. httpd.serve_forever()
  35. if __name__ == '__main__':
  36. main()

comments powered by Disqus