OSError:[Errno 9] python 3中的文件描述符错误

时间:2013-10-27 23:00:02

标签: python sockets webserver

我是一名初级/中级程序员,目前正在尝试用Python 3编写一个简单的Web服务器。但是,每当我运行模块时,我都会得到OSError:[Errno 9]错误的文件描述符。我在互联网上寻找答案,但我似乎无法自己想出这个。这是代码和回溯:

#import socket module

from socket import *

serverSocket=socket(AF_INET,SOCK_STREAM)

#Prepare a server socket

serverSocket.bind(('IP address', 8000))
serverSocket.listen(1)

while True:
#Establish the connection

 print('Ready to serve...')

 (connectionSocket, addr) = serverSocket.accept()

 print ('connected from',addr)

 try:


      message=connectionSocket.recv(1024)
      filename=message.split()[1]
      print (filename)

      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')

 #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 as err:
      print ('IO error')


           #Send response message for file not found

      connectionSocket.send(b'file not found')

                #Close client socket
      connectionSocket.close()
      serverSocket.close()

回溯:

Traceback (most recent call last):
  File "/Users/BigRed/Desktop/SOS/webServer.py", line 17, in <module>
    (connectionSocket, addr) = serverSocket.accept()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socket.py", line       184, in accept
fd, addr = self._accept()
OSError: [Errno 9] Bad file descriptor

1 个答案:

答案 0 :(得分:5)

当有OIError时,您正在呼叫serverSocket.close()。但是当您重新进入while循环时,如果没有调用serverSocket.accept(),则会调用serverSocket=socket(AF_INET,SOCK_STREAM),但这会失败,因为您调用了close()

请参阅此post

希望帮助

PD: django开发人员不定期使用套接字。 =)