multithreading - Python multi threading HTTP server not working -
i trying create multi threaded web server in python, requests handled 1 one. after searching few hours, found link approved answer seems incorrect request on there handled 1 one. here code:
from basehttpserver import httpserver, basehttprequesthandler socketserver import threadingmixin import threading time import sleep class handler(basehttprequesthandler): def do_get(self): self.send_response(200) self.end_headers() sleep(5) message = threading.currentthread().getname() self.wfile.write(message) self.wfile.write('\n') return class threadedhttpserver(threadingmixin, httpserver): """handle requests in separate thread.""" if __name__ == '__main__': server = threadedhttpserver(('localhost', 8080), handler) print 'starting server, use <ctrl-c> stop' server.serve_forever()
i added "sleep(5)" 5 second delay handle request. after send multiple requests requests handled 1 one , each request took 5 seconds. unable find reason. me.
the key requirement here able have 5-second delay between send_response
, data returned. means need streaming; can't use threadingmixin
, gunicorn
, or other such hack.
you need this:
import time, socket, threading sock = socket.socket (socket.af_inet, socket.sock_stream) host = socket.gethostname() port = 8000 sock.bind((host, port)) sock.listen(1) http = "http/1.1 200 ok\ncontent-type: text/html; charset=utf-8\n\n" class listener(threading.thread): def __init__(self): threading.thread.__init__(self) self.daemon = true # stop python biting ctrl-c self.start() def run(self): conn, addr = sock.accept() conn.send(http) # serve infinite stream = 0 while true: conn.send("%i " % i) time.sleep(0.1) += 1 [listener() in range(100)] time.sleep(9e9)
Comments
Post a Comment