Answers for "websocket api python on close"

0

websocket api python on close

import asyncio
import datetime
import random
import websockets

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        try:
            await websocket.send(now)
        except websockets.exceptions.ConnectionClosed:
            print("Client disconnected.  Do cleanup")
            break             
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Posted by: Guest on March-18-2021

Python Answers by Framework

Browse Popular Code Answers by Language