Below you will find the skeleton code for the Web server. You are to complete th
ID: 3682522 • Letter: B
Question
Below you will find the skeleton code for the Web server. You are to complete the skeleton code or build your own code. In the skeleton code, the places where you need to fill in code are marked with #Fill. Each place may require one or more lines of code. (You may need to add additional lines other than the places marked with #Fill. The following just provides an example, you may not follow the example)
Skeleton Python Code for the Web Server
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = #Fill
try:
message = #Fill nd
filename = message.split()[1]
f = open(filename[1:])
outputdata = #Fill
#Send one HTTP header line into socket
#Fill
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill
#Close client socket
#Fill
serverSocket.close()
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = #Fill
try:
message = #Fill nd
filename = message.split()[1]
f = open(filename[1:])
outputdata = #Fill
#Send one HTTP header line into socket
#Fill
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill
#Close client socket
#Fill
serverSocket.close()
Explanation / Answer
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('127.0.0.1',80))
serverSocket.listen(5)
while True:
#Establish the connection
print 'Ready to serve...'
(connectionSocket, addr) = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK ')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
connectionSocket.send('file not found')
#Close client socket
connectionSocket.close()
serverSocket.close()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.