首页 > 解决方案 > 服务器套接字编程找不到文件

问题描述

在这个程序中,我试图开发一个一次处理一个 HTTP 请求的 Web 服务器。Web 服务器应该接受并解析 HTTP 请求,从服务器的文件系统中获取请求的文件,创建一个 HTTP 响应消息,该消息由请求的文件和标题行组成,然后将响应直接发送给客户端。如果服务器中不存在请求的文件,则服务器应返回 HTTP 404“未找到”消息。

这是我试图使它工作的代码:

#import socket module
from socket import *
serverPort = 6789
import sys #In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket on a particular port
# Fill in code to set up the port
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept() # Fill in code to get a connection
    try:
        message = connectionSocket.recv(1024)#Fill in code to read GET request
        filename = message.split()[1]
        # Fill in security code
        f = open(filename)
        outputdata = f.read()# Fill in code to read data from the file
        # Send http HEADER LINE (s) into socket
        #Fill in code to send header(s)
        # Send the content of the requested file to the client
        print(outputdata)
        connectionSocket.send('\nHTTP/1.1 200 OK\n\n')
        connectionSocket.send(outputdata)
        for i in range(0, len(outputdata)):
          connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        #Fill in
        print ("404 Page Not Found")
        connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
        #Close client socket
        # Fill in
        connectionSocket.close
serverSocket.close()
sys.exit()

然后我尝试通过在浏览器地址栏中键入 localhost:6789/HelloWorld.html 来访问名为 HelloWorld.html 的文件,以使程序运行,但我收到此错误:

Ready to serve...
404 Page Not Found
Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 21, in <module>
    f = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: b'/HelloWorld.html'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 37, in <module>
    connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
TypeError: a bytes-like object is required, not 'str'

我收到 404 not found 错误,但我的 HTML 文件与我的 python 文件位于同一目录中。HelloWorld.html 与 python 文件位于同一桌面文件夹中。此外,当在网络浏览器中输入 localhost 时,浏览器会弹出以下内容: 在此处输入图像描述

标签: pythonfile-io

解决方案


如果文件存在于目录中,则可能与错误的文件名有关。我在文件名中看到它正在检查,'/HelloWorld.html'而它应该是'HelloWorld.html'.

因此,只需在您的代码中更新以排除前导斜杠。

filename = message.split()[1]

file= message.split()[1]
filename = file[1:]

推荐阅读