Python多线程HTTP服务器无法正常工作

时间:2017-08-20 18:09:33

标签: python multithreading http server python-multithreading

我正在尝试在python中创建多线程Web服务器,但请求是逐个处理的。搜索了几个小时后,我发现了这个link,但批准的答案似乎不正确,因为那里的请求也是逐个处理的。 这是代码:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
from 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 a separate thread."""

if __name__ == '__main__':
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

我添加了“sleep(5)”5秒延迟来处理请求。之后我发送了多个请求,但所有请求都是逐个处理的,每个请求花了5秒钟。我无法找到原因。帮助我。

1 个答案:

答案 0 :(得分:0)

这里的关键要求是能够在send_response和返回的数据之间有5秒的延迟。这意味着你需要流媒体;您无法使用ThreadingMixIngunicorn或任何其他此类黑客攻击。

你需要这样的东西:

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 from biting ctrl-C
        self.start()

    def run(self):
        conn, addr = sock.accept()
        conn.send(HTTP)

        # serve up an infinite stream
        i = 0
        while True:
            conn.send("%i " % i)
            time.sleep(0.1)
            i += 1

[Listener() for i in range(100)]
time.sleep(9e9)