Reputation: 87
I want to write code for a multi clients socket program, but I get Bad file descriptor, and I don't know how to fix it. this is my first code in python I'm new in python.
my code:
import socket
import os.path
from thread import *
host = '0.0.0.0'
port = 11111
#server_socket = socket.socket()
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
def clientthread(client_socket):
while True:
rqst = client_socket.recv(1024)
if ("GET" not in rqst) or (rqst == ""):
client_socket.send("HTTP/1.1 500 Internal Server Error\r\n")
FileName = rqst.split(" ")[1]
print "Client (%s, %s) connected" % client_address
print rqst
if os.path.isfile(os.getcwd() + FileName) == True:
f = open(os.getcwd() + FileName )
g = f.read()
response = 'HTTP/1.1 200 OK\r\n' + 'Content-Length: ' + str(len(g)) + '\r\n''' + g
client_socket.send(response)
print response
elif FileName == "/":
f = open(os.getcwd() + "/index.html")
g = f.read()
response = 'HTTP/1.1 200 OK\r\n' + 'Content-Length: ' + str(len(g)) + '\r\n''' + g
client_socket.send(response)
print response
elif FileName == "/for.html":
client_socket.send("HTTP/1.1 403 Forbidden\r\n\r\n")
print "HTTP/1.1 403 Forbidden\r\n\r\n"
elif FileName == "/move.html":
f = open(os.getcwd() + "/index2.html")
g = f.read()
client_socket.send(g)
client_socket.send('HTTP/1.1 302 Moved Temporarily\r\n')
print 'moved''http/1.1 302 Moved Temporarily\r\n'
elif "calculate-next?num=" in FileName:
num = int(FileName[FileName.find("=")+1:])+1
client_socket.send(str(num))
print str(num)
elif "calculate-area?" in FileName:
height = float(FileName[FileName.find("height")+7:FileName.find("&")])
width = float(FileName[FileName.find("width")+6:])
S = float((height*width)/2)
client_socket.send(str(S))
print str(S)
else:
response = "HTTP/1.1 404 Not Found\r\n"
client_socket.send(response)
print response
client_socket.close()
client_socket.close()
server_socket.close()
while True:
(client_socket, client_address) = server_socket.accept()
start_new_thread(clientthread ,(client_socket,))
my error:
Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\Eden\Desktop\HTTPserver\server2.py", line 15, in clientthread rqst = client_socket.recv(1024) File "C:\Python27\lib\socket.py", line 174, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: [Errno 9] Bad file descriptor
What should I do?
Upvotes: 0
Views: 3129
Reputation: 3804
You have a duplicate client_socket.close()
line indented in your inner while loop. This means that you try to recieve data from the closed socket, which raises that error. Also, why are you closing the server_socket
in the clientthread
method.
Upvotes: 0