Reputation: 663
I'm trying to create a simple server, and keep getting the following error in IDLE:
File "C:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
This is my code. I've tried understanding why, and it has something to do with closing one of the sockets and then trying to use it again but I don't really get how I'm supposed to fix it. Any and all help is appreciated. :)
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
port=10101
serverSocket.bind(('',port))
serverSocket.listen(5)
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
try:
message = serverSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
connectionSocket.send('HTTP/1.1 404 File not found\r\n\n')
connectionSocket.close()
serverSocket.close()
serverSocket.close()
Upvotes: 1
Views: 4591
Reputation: 392
A couple of things:
As user27994550 put in his code, you want to use
message = connectionSocket.recv(1024)
to receive messages, not the server socket.
The other thing that both of your codes missed is you don't want to call
serverSocket.close()
in your except function unless you're closing the program overall. If you close the server socket, the next time you call
connectionSocket, addr = serverSocket.accept()
you won't be able to accept another connection. Hope this helps!
Upvotes: 1
Reputation: 206
You are trying to use the "message" variable data without checking if its empty. I think this might be the problem.
Try this:
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
port=10101
serverSocket.bind(('localhost',port))
serverSocket.listen(5)
while True:
print('Ready to server')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
if message != "": #Checking if empty
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
connectionSocket.send('HTTP/1.1 404 File not found\r\n\n')
connectionSocket.close()
serverSocket.close()
Upvotes: 0