Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import datetime
- import random
- import websockets
- message = ''
- async def daemon():
- while True:
- print('daemon:', message)
- if message == 'STOP':
- stop.set_result(None)
- await asyncio.sleep(2)
- async def main():
- async with websockets.serve(handler, '127.0.0.1', 5678):
- await stop
- async def handler(websocket, path):
- global message
- while True:
- now = datetime.datetime.utcnow().isoformat() + 'Z'
- await websocket.send(now)
- await asyncio.sleep(random.random() * 3)
- while True:
- message = await websocket.recv()
- await consumer(message)
- 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()
- stop = asyncio.Future()
- asyncio.ensure_future(daemon())
- asyncio.get_event_loop().run_until_complete(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement