-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonefilewebserver.py
More file actions
56 lines (42 loc) · 1.49 KB
/
onefilewebserver.py
File metadata and controls
56 lines (42 loc) · 1.49 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python3
import datetime
import sys
import socket
from threading import Thread
HOST = '192.168.0.122'
PORT = 80
serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSock.bind((HOST,PORT))
serverSock.listen(1)
def secretary(): #The secretary will serve you the proper resource :3
while True:
clientSock, clientAddr = serverSock.accept()
clientAddr=clientAddr[0] #actual addr is first element of a tuple
request = clientSock.recv(1024).decode()
print(request)
#resource will contain the requested htdoc
resource = request.split()
resource = resource[1]
if resource[0] == '/':
resource = resource.replace('/','',1)
if resource == '':
resource = 'index.html'
resource = 'www/'+resource
#crafting response
respCode = '200 OK'
try:
body = open(resource,'r')
except FileNotFoundError:
body = open('www/404.html','r')
respCode = '404 Not Found'
except IsADirectoryError:
body = open('www/403.html','r')
respCode = '403 Forbidden'
response = f'HTTP/1.1 {respCode}\n\n{body.read()}'
clientSock.send(response.encode())
clientSock.close()
try:
secretary()
except KeyboardInterrupt:
print("Killed by keyboard")