Skip to content

Instantly share code, notes, and snippets.

@jamesstidard
Last active February 25, 2017 00:39
Show Gist options
  • Save jamesstidard/eb619fcd598bb6e3eb946f8dca93cf32 to your computer and use it in GitHub Desktop.
Save jamesstidard/eb619fcd598bb6e3eb946f8dca93cf32 to your computer and use it in GitHub Desktop.
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)
while True:
try:
message = await ws.recv()
except ConnectionClosed:
ws_clients.remove(ws)
break
else:
await broadcast(message)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment