2019年8月

import asyncio
import datetime
import websockets


async def producer(ws, path):
    while 1:
        await asyncio.sleep(1)
        now = datetime.datetime.utcnow().isoformat() + "T" + '1'
        await ws.send(now)


async def now(ws, path):
    while 1:
        await asyncio.sleep(3)
        now = datetime.datetime.utcnow().isoformat() + "Z" + "3"
        await ws.send(now)


async def handler(websocket, path):
    # 协程并发执行的例子
    await asyncio.gather(now(websocket, path), producer(websocket, path), return_exceptions=True)

start_server = websockets.serve(handler, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()