我正在处理的代码编译得很好,但是在 Web 服务器将消息发送到客户端之后,服务器退出并出现以下错误。此外,在使用 serverAddr:serverPort/test.html 时,我的代码似乎永远不会到达 IOError 块。哪个应该返回 '404 page not found' 通过查看回溯,我认为这可能只是我的机器设置的问题,但我不完全确定。我的代码可能有问题吗?
#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()
Traceback:
Server is ready to receive
Ready to serve...
Ready to serve...
Traceback (most recent call last):
File "hw2.py", line 35, in <module>
connectionSocket, addr = serverSocket.accept()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor