Python 3中的OSError: [Errno 9] Bad file descriptor

5

我是一名初中级程序员,目前正在尝试使用Python 3编写一个简单的Web服务器。但是,每当我运行模块时,都会出现OSError:[Errno 9] Bad file descriptor错误。我已经在互联网上搜索了很多答案,但似乎无法自行解决这个问题。以下是代码和回溯信息:

#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

你有遇到任何IOError错误吗? - Leandro
是的,可能不需要Django标签,但出于某种原因建议使用。想着也许Django用户会知道。无论如何,当代码执行时确实出现了IO错误: 准备好服务... 连接自('10.0.0.6', 50077) b'/helloworld.html' IO错误 准备好服务... - yosh315
可能是重复的问题:Python sockets. OSError: [Errno 9] Bad file descriptor - Evan Carroll
我在 Django 项目的测试代码中遇到了这个错误,因为我没有模拟一个新的 API 调用 - 模拟解决了我的问题。 - cellepo
1个回答

9
当有OIError时,你会调用serverSocket.close()。但当你重新进入while循环时,你调用serverSocket.accept()而没有调用serverSocket=socket(AF_INET,SOCK_STREAM),这会导致失败,因为你已经调用了close()
参考这篇文章
希望能够帮助你。
附注:Django开发人员不经常使用socket。 =)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接