如何在 Python Tornado 中将 websocket 传递给子进程?

问题描述:

我有一个带有一些 Websockethandler 的 Tornado 服务器.我想创建一个工作人员池,以便将工作人员作为子进程启动并将 websocket 连接传递给工作人员.工作人员完成后,应向客户端发送答复.

I have a Tornado-server with some Websockethandler. I want to make a pool of workers in order to start a worker as a child process and to pass websocket connection to the worker. After the worker has finished it should send an answer to the client.

def worker(message):
    inp_dict = json.loads(message)
    t = inp_dict["time"]
    time.sleep(t)
    return "Hello, World! "*int(t)

class WebSocket(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        print("WebSocket opened")

    def on_message(self, message):    
        self.write_message(worker(message))

    def on_close(self):
        print("WebSocket closed")

怎么做?

不支持在进程之间传递连接.相反,将连接留在主进程中并使用例如一个 multiprocessing.Queue 来回发送简单对象(纯旧数据)到子进程.

Passing connections between processes is not supported. Instead, leave the connections in the main process and use e.g. a multiprocessing.Queue to send simple objects (plain old data) back and forth to the child processes.