How to parse an HTTP request in python (custom web server) -
i trying create multi-threaded web server in python. have managed work basic text, i'm having trouble adapting http.
also crashes when sending request, not crash when using 'connect'. not setting server correctly on localhost:port ?
the main problem however, have client socket, not know how extract request data it.
#! /usr/bin/env python3.3 import socket, threading, time, sys, queue #initial number of worker threads knumthreads = 50 #queue of incoming requests connections = queue.queue(-1) class request_handler(threading.thread): def __init__(self): threading.thread.__init__(self) def run(self): while(true): #get request socket data queue global connections self.connection = connections.get() self.addr = self.connection[1] self.socket = self.connection[0] #i have socket, how parse request here? #also there better way respond manually create response here? self.response = 'http/1.1 200 ok/ncontent-type: text/html; charset=utf-8/n/n <html><body>hello world</body></html>' print("got here") self.socket.send(self.response.encode('utf-8')) self.socket.close() requests.task_done() #creates knumthreads threads handle requests def create_threads(): n in range(0, knumthreads): rh = request_handler() rh.start() def main(): s = socket.socket() port = int(sys.argv[1]) #sets server locally s.bind(('127.0.0.1', port)) s.listen(100) #create worker threads create_threads() #accept connections , add them queue while(true): c, addr = s.accept() connections.put_nowait((c, addr)) if __name__ == '__main__': main()
you need receive data connection this:
while(true): c, addr = s.accept() data = c.recv(1024) print(data) connections.put_nowait((c, addr))
refer http spec on how read request
http://www.w3.org/protocols/rfc2616/rfc2616-sec4.html#sec4.4
Comments
Post a Comment