Skip to content

Instantly share code, notes, and snippets.

@jamesstidard
Last active February 24, 2017 22:21
Show Gist options
  • Save jamesstidard/2a38ffeff8861c708562f94b84b2137f to your computer and use it in GitHub Desktop.
Save jamesstidard/2a38ffeff8861c708562f94b84b2137f to your computer and use it in GitHub Desktop.
import asyncio
import websockets
from websockets.exceptions import ConnectionClosed
connected = set()
async def suppress(f, *, exception):
try:
return await f
except exception:
pass
async def broadcast(message):
global connected
broadcasts = (ws.send(message) for ws in connected)
broadcasts = [suppress(f, exception=ConnectionClosed) for f in broadcasts]
await asyncio.wait(broadcasts)
async def handler(websocket, path):
global connected
connected.add(websocket)
while True:
try:
message = await websocket.recv()
except ConnectionClosed:
connected.remove(websocket)
break
else:
await broadcast(message)
start_server = websockets.serve(handler, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment