Last active
June 30, 2025 05:31
-
-
Save pajaydev/41b40f7f71bda0f01e7fbdbc44daf563 to your computer and use it in GitHub Desktop.
HTTP server implementation in python
This file contains hidden or 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 | |
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
# use the host and port where your web server is running | |
my_socket.connect(('127.0.0.1', 8080)) | |
cmd = 'GET http://127.0.0.1/robot.txt HTTP/1.0\r\n\r\n'.encode() | |
my_socket.send(cmd) | |
while True: | |
data = my_socket.recv(512) | |
if len(data) < 1: | |
break | |
print(data.decode(), end='') | |
my_socket.close() |
This file contains hidden or 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 | |
PORT = 8080 | |
HOST = "127.0.0.1" | |
# Create a socket with TCP protocol and IPV4 address | |
http_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
http_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
# Bind host and port | |
http_socket.bind((HOST, PORT)) | |
# Listen for connections | |
http_socket.listen(1) | |
print(f'Listening on port: {PORT}') | |
while True: | |
client_socket, client_addr = http_socket.accept() | |
print(f'establishing connection {client_addr}') | |
# data is exchanged | |
incoming_data = client_socket.recv(1024) | |
print(f'Incoming data: {incoming_data.decode()}') | |
if not incoming_data: | |
break | |
# get method and path from http request | |
request_line = incoming_data.decode().splitlines()[0] | |
method, path,_ = request_line.split() | |
if path != '/': | |
body = f"<html><body><h2>Responding from HTTP server, you are trying to access {path} </h2></body></html>" | |
else: | |
body = f"<html><body><h2>Responding from HTTP server</h2></body></html>" | |
# Send basic http response | |
http_response = ( | |
"HTTP/1.1 200 OK\r\n" | |
"Content-Type: text/html; charset=utf-8\r\n" | |
"\r\n" | |
f"{body}\r\n\r\n" | |
) | |
client_socket.sendall(http_response.encode()) | |
# close connection | |
client_socket.close() | |
http_socket.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment