python bad file descriptor_OSError: [Errno 9] Bad file descriptor in python 3

问题

I'm a beginning/intermediate level programmer currently trying to write a simple web server in Python 3. However, whenever I run the module I get OSError: [Errno 9] Bad file descriptor. I've scoured the internet looking for answers, but I can't seem to figure this one out on my own. Here is the code and traceback:

#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:

Traceback (most recent call last):

File "/Users/BigRed/Desktop/SOS/webServer.py", line 17, in

(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:

When there is a OIError, you're calling serverSocket.close(). But when you re-enter in the while loop, you call serverSocket.accept() without call serverSocket=socket(AF_INET,SOCK_STREAM), and this fails, because you've called the close()

See this post

Hope help

PD: django developers don't use socket regularly. =)

来源:https://stackoverflow.com/questions/19624684/oserror-errno-9-bad-file-descriptor-in-python-3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值