服务器套接字编程找不到文件

问题描述 投票:-1回答:1

[在此程序中,我正在尝试开发一个可同时处理一个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文件位于同一桌面文件夹中。另外,在Web浏览器中输入localhost时,浏览器会弹出以下内容:enter image description here

python file-io
1个回答
0
投票

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

因此只需在代码中进行更新即可排除前导斜杠。

filename = message.split()[1]

收件人

file= message.split()[1]
filename = file[1:]
© www.soinside.com 2019 - 2024. All rights reserved.