繁体   English   中英

TypeError: bytes-like object 是必需的,而不是 'str'

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

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

本地主机:6789/hello.html

output 将是 = 你好,但如果他写

本地主机:6789/hello1.html

那么 output 将在浏览器中显示为“404 not found”。

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

 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM