1# this program serves files from the server, if not found then returns 404
2
3
4# Import socket module
5from socket import *
6
7# Create a TCP server socket
8#(AF_INET is used for IPv4 protocols)
9#(SOCK_STREAM is used for TCP)
10
11serverSocket = socket(AF_INET, SOCK_STREAM)
12
13# Assign a port number
14serverPort = 6789
15
16# Bind the socket to server address and server port
17serverSocket.bind(("", serverPort))
18
19# Listen to at most 1 connection at a time
20serverSocket.listen(1)
21
22# Server should be up and running and listening to the incoming connections
23while True:
24 print('Ready to serve...')
25
26 # Set up a new connection from the client
27 connectionSocket, addr = serverSocket.accept()
28
29 # If an exception occurs during the execution of try clause
30 # the rest of the clause is skipped
31 # If the exception type matches the word after except
32 # the except clause is executed
33 try:
34 # Receives the request message from the client
35 message = connectionSocket.recv(1024)
36 # Extract the path of the requested object from the message
37 # The path is the second part of HTTP header, identified by [1]
38 filename = message.split()[1]
39 # Because the extracted path of the HTTP request includes
40 # a character '\', we read the path from the second character
41 f = open(filename[1:])
42 # Store the entire contenet of the requested file in a temporary buffer
43 outputdata = f.read()
44 # Send the HTTP response header line to the connection socket
45 connectionSocket.send(str.encode("HTTP/1.1 200 OK\r\n\r\n"))
46
47 # Send the content of the requested file to the connection socket
48 for i in range(0, len(outputdata)):
49 connectionSocket.send(str.encode(outputdata[i]))
50 connectionSocket.send(str.encode("\r\n"))
51
52 # Close the client connection socket
53 connectionSocket.close()
54
55 except IOError:
56 # Send HTTP response message for file not found
57 connectionSocket.send(str.encode("HTTP/1.1 404 Not Found\r\n\r\n"))
58 connectionSocket.send(str.encode("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n"))
59 # Close the client connection socket
60 connectionSocket.close()
61
62serverSocket.close()
63
64