经TCP连接向请求的浏览器发送响应。如果浏览器请求一个在该服务器中不存在的文件,服务器应当返回一个“404 Not Found”差错报文。
代码实现
#import socket module
from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
#Prepare a server socket
serverSocket.bind(('',80))
serverSocket.listen(5)
while True:
print('Ready to server')
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
header ='\nHTTP/1.1 200 OK\n\n'
connectionSocket.send(header.encode('utf-8'))
#Send the content of the requested file to the client
for i in range(0,len(outputdata)):
connectionSocket.send(outputdata[i].encode('utf-8'))
connectionSocket.close()
except Exception:
#Send response message for file not found
header = '\nHTTP/1.1 404 Not Found\n\n'
connectionSocket.send(header.encode('utf-8'))
#Close client socket
connectionSocket.close()