我们正在学习网络中的套接字,我们的任务是在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)。如何获取要打印的错误消息?
答案 0 :(得分:1)
for i in range(0, len(outputdata.encode())): connectionSocket.send(outputdata.encode())
此代码: