TypeError: bytes-like object is required, not 'str'

TypeError: bytes-like object is required, not 'str'

下面代码的目的是,检查服务器是否 运行 和 HTML 文件代码是否可访问,如果不是则发送错误“404 Not Found”。例如:如果用户写

localhost:6789/hello.html

输出将是 = hello 但如果他写

localhost:6789/hello1.html

那么在浏览器中输出将是“404 not found”。

但是下面的代码适用于第一个输出,但对于第二个输出,它给了我以下错误。

 connectionSocket.send("\nHTTP/1.1 200 OK\n")
TypeError: a bytes-like object is required, not 'str'

完整的实现代码如下。

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

# Create a TCP server socket
# (AF_INET is used for IPv4 protocols)
# (SOCK_STREAM is used for TCP)
serverPort = 6789
serverSocket = socket(AF_INET, SOCK_STREAM)

'''***Prepare a server socket***'''

# Fill in start

serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print(f"The web server is up on the port {serverSocket}")
# Fill in end

while True:
    # Establish the connection
    print("Ready to serve...")
    # Fill in start
    connectionSocket, addr = serverSocket.accept()
    # Fill in end

    try:
        # Fill in start
        message = connectionSocket.recv(1024)
        print(message, "\n" '::', message.split()[0], "\n" ':', message.split()[1])
        filename = message.split()[1]
        print(filename, "||", filename[1:])
        # Fill in end
        f = open(filename[1:])
        outputData = f.read()
        # print(outputData)
        # Send one HTTP header line into socket
        # Fill in start
        connectionSocket.send("\nHTTP/1.1 200 OK\n")
       # connectionSocket.send(outputData)
        # 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()


    except IOError:
        # Send response message for file not found
        # Fill in start
        connectionSocket.send("\nHTTP/1.1 404 Not Found \n\r\n")
        # Fill in end
        # Close client socket
        # Fill in start
        connectionSocket.send("<html> <head> </head><body><h1> 404 Not Found </h1> </body></html>\r\n")
        connectionSocket.close()
    # Fill in end

serverSocket.close()
sys.exit()  # Terminate the program after sending the corresponding data

使用 b 将您的字符串转换为字节,如下所示

connectionSocket.send(b"\nHTTP/1.1 200 OK\n")