1
from socket import *
import logging
import threading

#define the class for thread

class multithreadHTTPServer(threading.Thread):

def __init__(self, clientSocket, address): 
    super(multithreadHTTPServer, self).__init__()
    self.socket = clientSocket
    self.add = address

def run(self):
    try:
        #increment the number of visit by one every time a client was connected
        global numberOfVisit
        numberOfVisit+=1


        #initialize the response body
        response_body = [
            '<html><body><h1>Hello, world!</h1>',
            '<p>This page is in location %(request_uri)r, was requested ' ,
            'using %(request_method)r, and with %(request_proto)r.</p>',
            '<p>Request body is %(request_body)r</p>' ,
            '<p>Actual set of headers received:</p>',
            '<ul>',
        ]

        #prepare the response that going to send back to client
        response_body.append('<p>Number of visit : '+str(numberOfVisit)+'</p>')
        response_body.append('</ul></body></html>')
        response_body_raw = ''.join(response_body)
        response_headers = {
                'Content-Type': 'text/html; encoding=utf8',
                'Content-Length': len(response_body_raw),
                'Connection': 'close',
            }

        response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in \
                                                response_headers.iteritems())
        #read the input from client
        sentence = connectionSocket.recv(1024)
        capitalizedSentence = sentence.upper()

        #send status code
        connectionSocket.send('HTTP/1.1 200 OK\nHTTP/1.1 200 OK\nHTTP 1.1 200 OK\n')
        print ('HTTP/1.1 200 OK\nHTTP/1.1 200 OK\nHTTP 1.1 200 OK\n')
        print(response_headers_raw)
        print('\n')
        print(response_body_raw)

        #send the info of header
        connectionSocket.send(response_headers_raw)
        connectionSocket.send('\n') # to separate headers from body

        #send the body of response
        #connectionSocket.send(response_body_raw)
        connectionSocket.close()
    except Exception:
        import traceback
        print traceback.format_exc()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('log')

logger.info('start running test.py')

#number of visit counter, port number, and host name
serverPort = 12445
numberOfVisit = 0;
hostName = gethostname()


#create and initialize the socket to the port and host name
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('0.0.0.0',serverPort))
#start listening
serverSocket.listen(5)

while 1:
connectionSocket, addr = serverSocket.accept()
#start a new thread to handle the connection for each client
newThread = multithreadHTTPServer(connectionSocket,addr)
newThread.start()

每当我使用 connectionSocket 发送响应时,都会出现运行时随机错误。错误是:

第 48 行,在运行 connectionSocket.send('HTTP/1.1 200 OK\n......')

文件“C:\Python27\lib\socket.py”,_dummy raise 错误(EBADF,'Bad file descriptor')中的第 170 行错误:[Errno 9] Bad file descriptor

4

0 回答 0