gpt4 book ai didi

Python Web 服务器套接字

转载 作者:可可西里 更新时间:2023-11-01 02:50:59 25 4
gpt4 key购买 nike

我必须用 Python 创建一个 Web 服务器。下面是我正在处理的代码。当我执行它时,我最初没有得到任何错误,它打印出“Ready to serve..”,但是在打开浏览器并运行 http://10.1.10.187:50997/HelloWorld.html 之后(HelloWorld 是一个 html 文件,与我的 python 代码位于同一文件夹中,而 10.1.10.187 是我的 IP 地址,50997 是服务器端口),我收到一个 TypeError 说“需要像对象的字节而不是 str”。请帮助我解决这个问题,如果需要任何其他修改,请告诉我。

    #Import socket module
from socket import *

#Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)

# Assign a port number
serverPort = 50997

serverSocket = socket(AF_INET, SOCK_STREAM)

#serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#print ("hostname is: "), gethostname()
#print ("hostname is: "), socket.gethostname()

# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))

# 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()

try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message

filename = message.split()[1]
print ("File name is: "), filename

f = open(filename[1:])

outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")

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("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()

serverSocket.close()

我得到的错误-

    Ready to serve...
Message is:
File name is:
Traceback (most recent call last):
File "intro.py", line 56, in <module>
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'

最佳答案

您需要使用文本格式将要发送的字符串转换为字节。 UTF-8 是一种很好的文本格式。您可以像这样实现此转换:

bytes(string_to_convert, 'UTF-8')

或者,在您的代码上下文中:

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

关于Python Web 服务器套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com