异常未处理IOError

时间:2013-10-21 02:01:02

标签: python

我似乎无法弄清楚为什么我的代码无法处理如果我的Web服务器不包含文件而报告错误的异常。在我的服务器的目录中,我有它的代码和HelloWorld.html。对于其他文件,它应报告错误。我正在查看我的代码,它似乎正在读取任何文件,只是说它的内容是空白而没有实际抛出文件不在服务器上的错误。这是怎么回事?

#Tasks: Create a socket, bind to a specific address and port, send and receive an HTTP        packet.
#Description: Web server should handle one HTTP request at a time. So the serve closes its TCP connection after response.
#Accept and parse the HTTP request, get the requested file from the server (i.e.   HelloWorld.html), create a response
#message with the requested file and header lines, then send the response to the client.
#Error handling: If file not found then send HTTP "404 Not Found" Message back to client.

#import socket module: here we are using a low-level networking class from Python
from socket import * 

#create the socket that belongs to the server.
#AF_INTET represents the address families and protocols.
#SOCK_STREAM represents the socket type
serverSocket = socket(AF_INET, SOCK_STREAM) 

#Prepare a server socket 

#Define variable for serverPort; we'll use the one in the helper page of the book
serverPort = 51350
#Define host address
serverHost = ''

#Bind the socket to the local host machine address and port
serverSocket.bind((serverHost, serverPort))

#Listen for TCP connections from the client
serverSocket.listen(1)

#Verify setup for receiving
print 'Server is ready to receive'

while True: 
 #Establish the connection 
 print 'Ready to serve...' 
 #When the server receive a request from the client it must establish a new connectionSocket and begin taking in the data.
 connectionSocket, addr = serverSocket.accept()
 try: 
 #Take data from connectionSocket and place in message.
 #.recvfrom doesn't work because it expects data and return address variables.
    message = connectionSocket.recv(1024) 

    #uncomment for header information
    #print message

     #parse the message
    filename = message.split()[1] 
    f = open(filename[1:]) 
    outputdata = f.read();

 #Send one HTTP header line into socket 
    connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')

 #Send the content of the requested file to the client 
    for i in range(0, len(outputdata)): 
        connectionSocket.send(outputdata[i]) 

    connectionSocket.close() 

 except IOError:

 #Send response message for file not found 
    connectionSocket.send('404 Not Found')
    connectionSocket.close()

 #Close client socket 
 serverSocket.close() 

1 个答案:

答案 0 :(得分:2)

也许您需要"HTTP/1.1 404 Not Found\r\n\r\n"而不是"404 Not Found"

此外,您似乎在循环中关闭serverSocket,因此下一个accept()失败。