套接字编程:TypeError: a bytes-like object is required, not 'str'

发布于 2025-01-11 11:15:55 字数 2837 浏览 0 评论 0原文

我的 python 代码出现以下错误 TypeError: a bytes-like object is required, not 'str' 我按照这里的另一篇文章说添加 UTF-8 作为我的 connectionSocket.send 的参数,但它仍然给我错误

# Import socket module

from socket import *

import socket  # Alternative (better) syntax

# Create a TCP server socket

# (AF_INET is used for IPv4 protocols)

# (SOCK_STREAM is used for TCP)

# serverSocket = socket(AF_INET, SOCK_STREAM)

# Alternative (better) syntax
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Assign a port number

serverPort = 6079

# Bind the socket to server address and server port

serverSocket.bind(("", serverPort))

# or

# serverSocket.bind((gethostname(), serverPort))

# serverSocket.bind((socket.gethostname(), serverPort)) # Alternative (better) syntax

# Listen to at most 1 connection at a time

serverSocket.listen(1)

# Server should be up and running and listening to the incoming connections

while True:

    print('Ready to serve...')

    # Set up a new connection from the client

    connectionSocket, addr = serverSocket.accept()

    # If an exception occurs during the execution of try clause

    # the rest of the clause is skipped

    # If the exception type matches the word after except

    # the except clause is executed

    try:

        # Receives the request message from the client

        message = connectionSocket.recv(1024)

        print('Message is: '), message

        # Extract the path of the requested object from the message

        # The path is the second part of HTTP header, identified by [1]

        filename = message.split()[1]

        print('File name is: '), filename

        # Because the extracted path of the HTTP request includes

        # a character '/', we read the path from the second character

        f = open(filename[1:], 'r')

        # Store the entire contenet of the requested file in a temporary buffer

        outputdata = f.read()

        # Send the HTTP response header line to the connection socket

        connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n","UTF-8")

        # Send the content of the requested file to the connection socket

        for i in range(0, len(outputdata)):

            connectionSocket.send(outputdata[i])

        connectionSocket.send("\r\n")

        # Close the client connection socket

        connectionSocket.close()

    except IOError:

        # Send HTTP response message for file not found

        connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n", "UTF-8"))
        connectionSocket.send(bytes(
            "<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n", "UTF-8"))

        # Close the client connection socket

        connectionSocket.close()

serverSocket.close()

I have the following error for my python code TypeError: a bytes-like object is required, not 'str' I followed another post on here saying to add UTF-8 as a parameter for my connectionSocket.send but it still gives me errors

# Import socket module

from socket import *

import socket  # Alternative (better) syntax

# Create a TCP server socket

# (AF_INET is used for IPv4 protocols)

# (SOCK_STREAM is used for TCP)

# serverSocket = socket(AF_INET, SOCK_STREAM)

# Alternative (better) syntax
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Assign a port number

serverPort = 6079

# Bind the socket to server address and server port

serverSocket.bind(("", serverPort))

# or

# serverSocket.bind((gethostname(), serverPort))

# serverSocket.bind((socket.gethostname(), serverPort)) # Alternative (better) syntax

# Listen to at most 1 connection at a time

serverSocket.listen(1)

# Server should be up and running and listening to the incoming connections

while True:

    print('Ready to serve...')

    # Set up a new connection from the client

    connectionSocket, addr = serverSocket.accept()

    # If an exception occurs during the execution of try clause

    # the rest of the clause is skipped

    # If the exception type matches the word after except

    # the except clause is executed

    try:

        # Receives the request message from the client

        message = connectionSocket.recv(1024)

        print('Message is: '), message

        # Extract the path of the requested object from the message

        # The path is the second part of HTTP header, identified by [1]

        filename = message.split()[1]

        print('File name is: '), filename

        # Because the extracted path of the HTTP request includes

        # a character '/', we read the path from the second character

        f = open(filename[1:], 'r')

        # Store the entire contenet of the requested file in a temporary buffer

        outputdata = f.read()

        # Send the HTTP response header line to the connection socket

        connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n","UTF-8")

        # Send the content of the requested file to the connection socket

        for i in range(0, len(outputdata)):

            connectionSocket.send(outputdata[i])

        connectionSocket.send("\r\n")

        # Close the client connection socket

        connectionSocket.close()

    except IOError:

        # Send HTTP response message for file not found

        connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n", "UTF-8"))
        connectionSocket.send(bytes(
            "<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n", "UTF-8"))

        # Close the client connection socket

        connectionSocket.close()

serverSocket.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自找没趣 2025-01-18 11:15:55

connectionSocket.send(b"\r\n")

connectionSocket.send(b"\r\n")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文