Last active
February 25, 2017 00:39
-
-
Save jamesstidard/eb619fcd598bb6e3eb946f8dca93cf32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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