gpt4 book ai didi

python - 如何触发 "except"?

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:18 24 4
gpt4 key购买 nike

我们正在学习网络中的套接字,我们的任务是用 Python 填写模板(老师使用 Python2.x,而我使用 Python3.x)。

    # Import socket module
from socket import *

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

# Assign a port number
serverPort = 6789

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

# 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:
# Receive the request message from the client
message = connectionSocket.recv(4096).decode()
# 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]
# Because the extracted path of the HTTP request includes
# a character '\', we read the path from the second character
f = open(filename[1:])
# 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").encode())

# Send the content of the requested file to the connection socket
for i in range(0, len(outputdata.encode())):
connectionSocket.send(outputdata.encode())
connectionSocket.send(("\r\n").encode())

# Close the client connection socket
connectionSocket.close()

break

except IOError:
# Send HTTP response message for file not found
connectionSocket.send(("HTTP/1.1 404 NOT FOUND\r\n").encode())
connectionSocket.send(("<html><head></head><body><h1>ERROR. TRY AGAIN</h1></body></html>\r\n").encode())
# Close the client connection socket
connectionSocket.close()

break

#Close the Socket
serverSocket.close()

我正在读入的文件是一个 .htm 文件:

<html><head><title>HTML Test File</title></head><body><h1>Trying to Get This Frickin' Program to Work</h1></body></html>

当我运行程序并输入:localhost:6789/TestFile.htm时,它会一遍又一遍地打印文件内容,并给出错误消息:第34行,indexerror:列表索引超出范围。 编辑:break处理错误消息,但文件仍在一遍又一遍地打印

我做错了什么?

编辑#2:现在我正在尝试进行错误处理,但它只是表明当我输入不存在的文件(即 localhost:6789/Test.htm)时没有发送任何数据)。如何打印错误消息?

最佳答案

  for i in range(0, len(outputdata.encode())):  
connectionSocket.send(outputdata.encode())

这段代码:

  • 对文本进行两次编码
  • 循环 121 次(这是您发布的文件的长度,编码为 ASCII 或 UTF-8)
  • 每次发送整个文件 121 次

关于python - 如何触发 "except"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789759/

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