Advertisement
Guest User

Untitled

a guest
Oct 18th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. import asyncio
  2. import datetime
  3. import random
  4. import websockets
  5. message = ''
  6.  
  7.  
  8. async def daemon():
  9. while True:
  10. print('daemon:', message)
  11. if message == 'STOP':
  12. stop.set_result(None)
  13. await asyncio.sleep(2)
  14.  
  15. async def main():
  16. async with websockets.serve(handler, '127.0.0.1', 5678):
  17. await stop
  18.  
  19.  
  20. async def handler(websocket, path):
  21. global message
  22. while True:
  23. now = datetime.datetime.utcnow().isoformat() + 'Z'
  24. await websocket.send(now)
  25. await asyncio.sleep(random.random() * 3)
  26. while True:
  27. message = await websocket.recv()
  28. await consumer(message)
  29. consumer_task = asyncio.ensure_future(consumer_handler(websocket))
  30. producer_task = asyncio.ensure_future(producer_handler(websocket))
  31. done, pending = await asyncio.wait(
  32. [consumer_task, producer_task],
  33. return_when=asyncio.FIRST_COMPLETED,
  34. )
  35.  
  36. for task in pending:
  37. task.cancel()
  38.  
  39.  
  40. stop = asyncio.Future()
  41. asyncio.ensure_future(daemon())
  42. asyncio.get_event_loop().run_until_complete(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement