Untitled
unknown
python
2 years ago
2.5 kB
7
Indexable
import socket import os # Define socket host and port SERVER_HOST = '0.0.0.0' SERVER_PORT = 8080 # Create socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Reuse the socket server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind to the address server_socket.bind((SERVER_HOST, SERVER_PORT)) # Listen for incoming connections server_socket.listen(1) print(f"Listening on port {SERVER_PORT} ...") # HTTP response templates HTTP_HEADER_TEMPLATE = "HTTP/1.1 {status_code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {content_length}\r\n\r\n" HTTP_404_BODY = "<html><body><h1>404 Not Found</h1></body></html>" def generate_headers(method, file_path): if not os.path.isfile(file_path): headers = HTTP_HEADER_TEMPLATE.format(status_code=404, reason="Not Found", content_type="text/html", content_length=len(HTTP_404_BODY)) return headers, HTTP_404_BODY else: file_size = os.path.getsize(file_path) headers = HTTP_HEADER_TEMPLATE.format(status_code=200, reason="OK", content_type="text/html", content_length=file_size) return headers, None def handle_request(client_connection): request = client_connection.recv(1024).decode() headers, body = request.split('\r\n', 1) request_line = headers.splitlines()[0] request_method, path, _ = request_line.split() # Remove the leading '/' from the path file_path = path.lstrip('/') # Default file path if file_path == '': file_path = 'index.html' headers, body = generate_headers(request_method, file_path) # Send HTTP headers client_connection.sendall(headers.encode()) # If it's a GET request, send the file content if request_method == 'GET' and body is None: with open(file_path, 'rb') as file: while True: file_data = file.read(1024) if not file_data: break client_connection.sendall(file_data) # If it's a HEAD request or file not found, we don't send the file content elif body is not None: client_connection.sendall(body.encode()) # Handle client requests try: while True: # Wait for client connections client_connection, client_address = server_socket.accept() handle_request(client_connection) # Close the client connection client_connection.close() except KeyboardInterrupt: print("Closing the server...") server_socket.close()
Editor is loading...
Leave a Comment