經(jīng)TCP連接向請求的瀏覽器發(fā)送響應(yīng)忘分。如果瀏覽器請求一個在該服務(wù)器中不存在的文件棋枕,服務(wù)器應(yīng)當返回一個“404 Not Found”差錯報文。
代碼實現(xiàn)
#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()