Python:与asyncio混淆。运行websockets示例,程序同时接收和发送消息

时间:2019-07-29 07:12:55

标签: python asyncio

我对asyncio有点困惑。

在以下代码中,我希望代理程序运行一个websocket,并在它收到时执行一些操作并做出响应。

到目前为止,这是我的代码。我不确定如何实现Producer()函数。 理想情况下,我希望这样做,以便一旦worker_recv_handler运行,它将激活生产者功能,然后将消息发送回去。回声功能。我该怎么办?

def __init__(self, stackl_url):
    logger.log("[Agent] Starting Agent '{}'".format(self))

    agent_worker_loop = asyncio.new_event_loop()
    agent_worker_thread = threading.Thread(target=self.run_worker_websocket, args=(agent_worker_loop,))
    agent_worker_thread.start()

def run_worker_websocket(self, loop):
    self.agent_websocket = websockets.serve(worker_connection_handler, get_agent_url())
    loop.run_until_complete(self.agent_websocket)
    loop.run_forever()

def get_agent_url(self):
    return { 'host' : socket.gethostbyname(socket.gethostname()), "port": 8889}

async def worker_connection_handler(websocket, path):
    worker_recv_task = asyncio.ensure_future(
        worker_recv_handler(websocket, path))
    worker_send_task = asyncio.ensure_future(
        worker_send_handler(websocket, path))
    done, pending = await asyncio.wait(
        [worker_recv_task, worker_send_task],
        return_when=asyncio.FIRST_COMPLETED,
    )
    for task in pending:
        task.cancel()

async def worker_recv_handler(websocket, path):
    async for message in websocket:
        logger.log("[Agent] Received message from Worker: '{}'".format(message))

async def worker_send_handler(websocket, path):
    while True:
        message = await producer()
        await websocket.send(message)

0 个答案:

没有答案