Very minimal example I was able to put together after some research. You can find this also on https://replit.com/@bluebrown/python-socket-html
import socket
s = socket.socket()
s.bind(('0.0.0.0', 8080))
s.listen(1)
with open('index.html', 'rb') as file:
html = file.read()
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
req = conn.recv(1024)
print('request:', req)
conn.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
conn.sendall(html)
Based on your request int he comments I have taken it a bit further. Not much though. Just enough to give you an idea what it takes to service different pages.
import socket
def parseRequest(request):
output = {}
r = request.decode("utf-8").split("\r\n")
parts = r[0].split(' ')
output["method"] = parts[0]
output["path"] = parts[1]
output["protocol"] = parts[2]
output["headers"] = { (kv.split(':')[0]): kv.split(':')[1].strip() for kv in r[1:] if (len(kv.split(':')) > 1) }
return output
s = socket.socket()
s.bind(('0.0.0.0', 8080))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
req = conn.recv(1024)
r = parseRequest(req)
path = r["path"][1:]
if (path == ""):
path = "index"
with open(f'{path}.html', 'rb') as file:
html = file.read()
conn.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())
conn.sendall(html)
You can check the updated repl.