python - 操作系统错误 : [Errno 9] Bad file descriptor in python 3

标签 python sockets webserver

我是一名初级/中级程序员,目前正在尝试使用 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

最佳答案

当出现 OIError 时,您将调用 serverSocket.close()。但是当你重新进入 while 循环时,你调用了 serverSocket.accept() 而没有调用 serverSocket=socket(AF_INET,SOCK_STREAM),这失败了,因为你'我们调用了 close()

查看此 post

希望得到帮助

PD: Django 开发人员不经常使用套接字。 =)

关于python - 操作系统错误 : [Errno 9] Bad file descriptor in python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624684/

相关文章:

python - 在 pandas(Python) 中减去按 id 分组的数据框中的连续行

Java、套接字、线程

python - 运行 'ipython notebook' 得到 [Errno 49] 无法分配请求的地址

java - netty.io 提供静态网页内容

python - 从 Gunicorn worker 本身获取 worker id

javascript - 不正确的 header 会阻止 Chrome 循环播放 HTML5 音频

python - 当我的 python ddos​​ 脚本运行时出现错误

python - 创建随机值并将其传递给具有硬边界的 Pandas 数据帧

Python 设置 1 和 True 的插值

java套接字读取网页内容