我在使用python从服务器获取数据时遇到了困难。每当我尝试访问我的测试html文件时,我的浏览器上都会收到Errno 9错误的文件描述符和“连接已重置”消息。代码如下:
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 12000
#Prepare a sever socket
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()#Accepts a TCP client connection, waiting until connection arrives
print 'Required connection', addr
try:
message = connectionSocket.recv(64)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.0 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!')
#Close client socket
connectionSocket.close()
serverSocket.close()
我不知道为什么我会收到此错误。我已经尝试从outputdata for循环外部移除关闭,这也不起作用。我尝试更改服务器端口,并以不同的顺序关闭套接字和服务器。
完整的引用是:
Traceback (most recent call last):
File "UDPServer.py", line 13, in <module>
connectionSocket, addr = serverSocket.accept()#Accepts a TCP client connection, waiting until connection arrives
File "C:\Anaconda\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "C:\Anaconda\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
答案 0 :(得分:1)
关闭后,您无法使用套接字。 socket.close()
的{{3}}说:
套接字对象的所有未来操作都将失败。
您可以在循环中创建一个新套接字。