首页 > 解决方案 > 列表索引超出范围防止 404 错误?

问题描述

我正在尝试完成此实验,但似乎无法使其正常工作。当我尝试获取服务器不存在的文件时,我得到了

此页面无法正常工作 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,我使用的是 Python 3。我做了一些小的语法调整来调整。

删除 print(message) 会在编译器中产生“File Recieved”,但浏览器中仍然没有 404 错误。8小时后我不知所措。

标签: pythonserver

解决方案


IndexError处理in的一种方法message.split()[1]是处理 and IndexErrorin message.split()[1];)

try:
    filename = message.split()[1]
except IndexError:
    send_404_response()
    continue

推荐阅读