-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.py
More file actions
64 lines (52 loc) · 2.46 KB
/
httpserver.py
File metadata and controls
64 lines (52 loc) · 2.46 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
57
58
59
60
61
62
63
64
#Name: Zaafira Hasan
#UCID: zfh4
#Section: CS 356-003
#! /usr/bin/env python3
# http server
import sys
import socket
import os.path,time
from os import path
from datetime import datetime
import re
now = datetime.now()
dt_string=now.strftime("%a, %d %b %Y %H:%M:%S %Z")
host = sys.argv[1]
port = int(sys.argv[2])
dataLen = 1000000
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind((host, port))
serverSocket.listen(1)
while True:
connectionSocket, address = serverSocket.accept()
data = connectionSocket.recv(dataLen)
print(data.decode())
unifRL = re.split('(\/)|( HTTP)|(Since: )|(\n)', data.decode())
filename=unifRL[5]
if (path.exists(filename)):
if "If-Modified-Since" in data.decode():
nmod=time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(os.path.getmtime(filename)))
unifRL = re.split('(\/)|( HTTP)|(Since: )|(\n)', data.decode())
modified=unifRL[30]
filename=unifRL[5]
if (nmod in modified):
shamh = "HTTP \/1.1 304 Not Modified\\r\\n"
connectionSocket.send(shamh.encode())
else:
nmod=time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(os.path.getmtime(filename)))
with open(filename) as myfile:
head = [next(myfile) for x in range(3)]
Modified = "HTTP/1.1 200 OK\r\n" + "Date: " + dt_string + "GMT\r\n" + "Last-Modified: " + nmod + " GMT\r\n" + "Content-Length: " + str(os.stat(filename).st_size) +"\r\n"+"Content-Type: text/html; charset=UTF-8\r\n"+"\r\n"+head[0] + head[1] + head[2]
print(Modified)
connectionSocket.send(Modified.encode())
else:
nmod=time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(os.path.getmtime(filename)))
with open(filename) as myfile:
head = [next(myfile) for x in range(3)]
Modified = "HTTP/1.1 200 OK\r\n" + "Date: " + dt_string + "GMT\r\n" + "Last-Modified: " + nmod + " GMT\r\n" + "Content-Length: " + str(os.stat(filename).st_size) +"\r\n" + "Content-Type: txt/html" + "; charset=UTF-8\r\n" + "\r\n" + head[0] + head[1] + head[2]
print(Modified)
connectionSocket.send(Modified.encode())
else:
NotFound = "HTTP/1.1 404 Not Found\r\n" + "Date:" + dt_string + "GMT\r\n" + "\r\n"
print(NotFound)
connectionSocket.send(NotFound.encode())