How do I organize bidirectional data exchange via websocket connection in aiohttp? For example, there is such a handler:

import asyncio q = asyncio.Queue() @asyncio.coroutine def websocket_handler(request): ws = web.WebSocketResponse() ws.start(request) while True: # input_msg = yield from ws.receive() output_msg = yield from q.get() ws.send_str(output_msg) return ws 

There is a queue through which messages for a specific connection arrive, and I send them to the client.

Where can I insert a line to receive messages from the client input_msg = yield from ws.receive() ?
Indeed, in this case, until one of the yield from operators completes, the second one does not begin, and it will turn out that I can either receive messages or send. What to do in this case?

    1 answer 1

     listener_task = asyncio.ensure_future(ws.receive()) producer_task = asyncio.ensure_future(producer()) done, pending = await asyncio.wait([listener_task, producer_task], return_when=asyncio.FIRST_COMPLETED) 

    Use this technique, and that you didn’t wait for the Korutin to cancel task.cancel () with this method.