Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- from sanic import Sanic
- from sanic.websocket import ConnectionClosed
- app = Sanic(__name__)
- ws_clients = set()
- async def broadcast(message):
- global ws_clients
- broadcasts = [ws.send(message) for ws in ws_clients]
- for result in asyncio.as_completed(broadcasts):
- try:
- await result
- except ConnectionClosed:
- pass
- @app.websocket("/ws")
- async def websocket(_, ws):
- global ws_clients
- ws_clients.add(ws)
- print(f'{len(ws_clients)} clients')
- while True:
- try:
- message = await ws.recv()
- except ConnectionClosed:
- ws_clients.remove(ws)
- print(f'{len(ws_clients)} clients')
- break
- except:
- print('yelp')
- else:
- await broadcast(message)
- if __name__ == '__main__':
- app.run(host="0.0.0.0", port=8000, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement