How to send message from the child process to webs

2019-05-26 19:48发布

I have the Tornado server. It receives messages from websocket-connections. I need to run the worker function as a separate process and the worker should answer to client. The main idea is to work in a parallel mode. Something like this

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

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

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

    def open(self):
        print("WebSocket opened")
        self.application.webSocketsPool.append(self)

    def on_message(self, message):
        for key, value in enumerate(self.application.webSocketsPool):
            if value == self:
                p = Process(target=worker, args=(value.ws_connection,message,))
                p.start()

    def on_close(self):
        print("WebSocket closed")
        for key, value in enumerate(self.application.webSocketsPool):
            if value == self:
                del self.application.webSocketsPool[key]

Of course, this doesn't work because of pickling error. How to solve this problem?

0条回答
登录 后发表回答