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

2024-10-06 20:36:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: theinsendmessagelinesocketfilenamefile
1条回答
网友
1楼 · 发布于 2024-10-06 20:36:13

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

看这个post

希望帮助

PD:django开发人员不经常使用socket。=)

相关问题 更多 >