Skip to content

Commit

Permalink
Improve getting started for -both- case (#144)
Browse files Browse the repository at this point in the history
* Improve getting started for -both- case

* Minor tweaks.
  • Loading branch information
bajamircea authored and aaugustin committed Nov 24, 2016
1 parent 858b261 commit c259545
Showing 1 changed file with 19 additions and 21 deletions.
40 changes: 19 additions & 21 deletions docs/intro.rst
Expand Up @@ -90,28 +90,26 @@ messages on the same connection.

::

async def handler(websocket, path):
async def consumer_handler(websocket):
while True:
message = await websocket.recv()
await consumer(message)

async def producer_handler(websocket):
while True:
listener_task = asyncio.ensure_future(websocket.recv())
producer_task = asyncio.ensure_future(producer())
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED)

if listener_task in done:
message = listener_task.result()
await consumer(message)
else:
listener_task.cancel()

if producer_task in done:
message = producer_task.result()
await websocket.send(message)
else:
producer_task.cancel()

(This code looks convoluted. If you know a more straightforward solution,
please let me know about it!)
message = await producer()
await websocket.send(message)

async def handler(websocket, path):
consumer_task = asyncio.ensure_future(consumer_handler(websocket))
producer_task = asyncio.ensure_future(producer_handler(websocket))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED,
)

for task in pending:
task.cancel()

Registration
............
Expand Down

0 comments on commit c259545

Please sign in to comment.