38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
import socket
|
|
|
|
PORT = 8080
|
|
HOST = 'localhost'
|
|
|
|
def http_server():
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
|
|
server.bind((HOST, PORT))
|
|
print(f"Server running on {HOST}:{PORT}")
|
|
|
|
server.listen()
|
|
|
|
while True:
|
|
conn, addr = server.accept()
|
|
with conn:
|
|
print('Connected by', addr)
|
|
request = conn.recv(1024).decode('utf-8')
|
|
print('Request:', request)
|
|
|
|
method, path, *_ = request.split()
|
|
|
|
if method == 'GET':
|
|
if path == '/':
|
|
with open('index.html', 'rb') as file:
|
|
content = file.read()
|
|
response = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n' + content
|
|
elif path == '/page1':
|
|
response = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nThis is page 1'
|
|
else:
|
|
response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\nPage not found'
|
|
else:
|
|
response = b'HTTP/1.1 405 Method Not Allowed\r\nContent-Type: text/html\r\n\r\nMethod not allowed'
|
|
|
|
conn.sendall(response)
|
|
|
|
if __name__ == '__main__':
|
|
http_server()
|