forked from NYUCyberFellows-CSGY6843/assignment2-webserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebServer.py
More file actions
executable file
·65 lines (45 loc) · 2.27 KB
/
webServer.py
File metadata and controls
executable file
·65 lines (45 loc) · 2.27 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
65
# import socket module
from socket import *
# In order to terminate the program
import sys
def webServer(port=13331):
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
serverSocket.bind(("", port))
#Fill in start
#Fill in end
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = #Fill in start -are you accepting connections? #Fill in end
try:
message = #Fill in start -a client is sending you a message #Fill in end
filename = message.split()[1]
#opens the client requested file.
#Plenty of guidance online on how to open and read a file in python. How should you read it though if you plan on sending it through a socket?
f = open(filename[1:], #fill in start #fill in end)
#fill in end
outputdata = b"Content-Type: text/html; charset=UTF-8\r\n"
#Fill in start -This variable can store your headers you want to send for any valid or invalid request.
#Content-Type above is an example on how to send a header as bytes
#Fill in end
#Send an HTTP header line into socket for a valid request. What header should be sent for a response that is ok?
#Note that a complete header must end with a blank line, creating the four-byte sequence "\r\n\r\n" Refer to https://w3.cs.jmu.edu/kirkpams/OpenCSF/Books/csf/html/TCPSockets.html
#Fill in start
#Fill in end
#Send the content of the requested file to the client
for i in f: #for line in file
#Fill in start - send your html file contents #Fill in end
connectionSocket.close() #closing the connection socket
except Exception as e:
# Send response message for invalid request due to the file not being found (404)
#Fill in start
#Fill in end
#Close client socket
#Fill in start
#Fill in end
#Commenting out the below, as its technically not required and some students have moved it erroneously in the While loop. DO NOT DO THAT OR YOURE GONNA HAVE A BAD TIME.
#serverSocket.close()
#sys.exit() # Terminate the program after sending the corresponding data
if __name__ == "__main__":
webServer(13331)