-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
41 lines (32 loc) · 1.07 KB
/
main.py
File metadata and controls
41 lines (32 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from socket import *
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 8080
server = socket(AF_INET, SOCK_STREAM)
server.bind((SERVER_HOST, SERVER_PORT))
server.listen(5)
print(f"server is listening on {SERVER_PORT}....\n")
while True:
client_socket, client_address = server.accept()
request = client_socket.recv(2048).decode()
print(request)
header = request.split("\n")
if len(header) > 0 and len(header[0].split()) >= 2:
first_header_component = header[0].split()
http_method = first_header_component[0]
path = first_header_component[1]
else:
client_socket.close()
continue
if http_method == "GET":
if path == "/":
with open("index.html") as fin:
content = fin.read()
elif path == "/book":
with open("book.json") as fin:
content = fin.read()
fin.close()
response = "HTTP/1.1 200 OK\n\n" + content
else:
response = "HTTP/1.1 405 Method Not Allowed\n\nAllow: GET"
client_socket.sendall(response.encode())
client_socket.close()