Created
June 11, 2024 04:18
-
-
Save mraza007/d0d9cfd07ed13390070633b9da1ce73c to your computer and use it in GitHub Desktop.
Simple Implementation of HTTP Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
# Define server address and port | |
HOST, PORT = "", 8000 | |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server_socket.bind((HOST, PORT)) | |
server_socket.listen(5) | |
print(f"Listening on port {PORT}") | |
while True: | |
client_connection, client_address = server_socket.accept() | |
request_data = client_connection.recv(1024) | |
print(request_data.decode("utf-8")) | |
response_body = """\ | |
<html> | |
<head><title>Hello</title></head> | |
<body><h1>Hello, World!</h1></body> | |
</html> | |
""" | |
# Define the HTTP response headers | |
http_response = f"""\ | |
HTTP/1.1 200 OK | |
Content-Type: text/html; charset=UTF-8 | |
Content-Length: {len(response_body)} | |
{response_body}""" | |
client_connection.sendall(http_response.encode("utf-8")) | |
client_connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment