我正在尝试完成本实验,但似乎无法使其正常工作。当我尝试获取服务器中不存在的文件时,会得到
此页面无效 127.0.0.1发送了无效的响应。 ERR_INVALID_HTTP_RESPONSE
我想得到的答复是
找不到404文件
当我尝试加载不存在的文件时,编译器对第16行说:
文件名= message.split()[1] IndexError:列表索引超出范围
代码已编译,我可以打开我的Hello World文件,但无法收到此404错误。我获得了基本代码,因此有些事情在不偏离课程材料的情况下是无法更改的。
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
serverPort = 7000
serverSocket.bind(('127.0.0.1', serverPort))
serverSocket.listen(5)
while True:
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
#Fill in start #Fill in end
try:
message = connectionSocket.recv(1024)
print (message)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
#Fill in start
connectionSocket.send('\nHTTP/1.x 200 OK\n'.encode())
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
print ('File Recieved')
except IOError:
connectionSocket.send('\n404 File Not Found\n'.encode())
connectionSocket.close()
#Close client socket
serverSocket.close()
sys.exit()
最基本的代码似乎是Python 2,而我使用的是Python3。我进行了一些小的语法调整以进行调整。
删除打印(消息)在编译器中产生“文件已接收”,但在浏览器中仍然没有404错误。 8小时后我无所适从。
答案 0 :(得分:0)
处理IndexError
中的message.split()[1]
的一种方法是处理IndexError
中的message.split()[1]
;)
try:
filename = message.split()[1]
except IndexError:
send_404_response()
continue