python - 如何触发 "except"?

标签 python sockets python-3.x serversocket

我们正在学习网络中的套接字,我们的任务是用 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/

相关文章:

javascript - Django 不应用链接的 js 和 css

python - 无论我做什么,都找不到 django-admin.py,即使它在我的路径中

Python 传递局部变量以在函数中进行修改

python-3.x - 如何在 docker 中运行 selenium+pytest?

python - 属性错误: module 'cupy' has no attribute 'array'

c++ - 如何将 C++ 库作为共享对象文件 (.so) 加载到 Python 中?

macos - 在 Mac OS X 中访问 unix 域套接字

python socket recv() 和信号

Java/JSP 发送TCP包并等待响应

python-3.x - 如何使用 Python 和 Beautiful Soup 修复 html 列表片段中丢失的 ul 标签