I'm having difficulty with getting data from a server in python. I'm getting Errno 9 bad file descriptor and a 'connection was reset' message on my browser whenever I try to access my test html file. The code is as follows:
我很难从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()
I can't tell why i am getting this error. I have tried removing the close from right outside the outputdata for loop, which didn't work either. I tried changing the server port, and closing the socket and server in different orders.
我不知道为什么会出现这个错误。我已经尝试从outputdata for loop的右侧删除close,它也不起作用。我尝试更改服务器端口,并按不同的顺序关闭套接字和服务器。
the full trackback is:
完整的引用:
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
1 个解决方案
#1
1
You can't use the socket once it's closed. The docs for socket.close()
say:
一旦插座关闭,你就不能使用它。足球的单据。close()说:
All future operations on the socket object will fail.
socket对象未来的所有操作都将失败。
You could create a new socket in the loop.
您可以在循环中创建一个新的套接字。
#1
1
You can't use the socket once it's closed. The docs for socket.close()
say:
一旦插座关闭,你就不能使用它。足球的单据。close()说:
All future operations on the socket object will fail.
socket对象未来的所有操作都将失败。
You could create a new socket in the loop.
您可以在循环中创建一个新的套接字。