套接字错误[Errno 9]错误的文件描述符HTTP服务器

时间:2015-11-14 12:08:28

标签: python sockets

我想为多客户端套接字程序编写代码, 但我得到了错误的文件描述符,我不知道如何解决它。 这是我在python中的第一个代码我是python中的新代码。

我的代码:

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,))

我的错误:

  

开始的线程中未处理的异常   Traceback(最近一次调用最后一次):     在clientthread中的文件“C:\ Users \ Eden \ Desktop \ HTTPserver \ server2.py”,第15行       rqst = client_socket.recv(1024)     文件“C:\ Python27 \ lib \ socket.py”,第174行,在_dummy中       引发错误(EBADF,'错误的文件描述符')   socket.error:[Errno 9]错误的文件描述符

我该怎么办?

1 个答案:

答案 0 :(得分:0)

你的内部while循环中有一个重复的client_socket.close()行缩进。这意味着您尝试从已关闭的套接字接收数据,这会引发该错误。另外,为什么要关闭server_socket方法中的clientthread