2016-02-11 242 views
0

我很難從python中的服務器獲取數據。每次嘗試訪問我的測試html文件時,我都會在瀏覽器中收到錯誤的Errno 9文件描述符和「連接已重置」消息。代碼如下:errno 9錯誤的文件描述符,基本的python服務器套接字

#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() 

我不能說爲什麼我得到這個錯誤。我試圖從輸出數據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 

回答

1

一旦它關閉,您不能使用套接字。 The docs for socket.close()說:

以後所有對套接字對象的操作都會失敗。

您可以在循環中創建一個新的套接字。

相關問題