| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import os |
| 4 |
import asyncio |
| 5 |
import websockets |
| 6 |
|
| 7 |
connections = set() |
| 8 |
|
| 9 |
async def echo(websocket, path): |
| 10 |
|
| 11 |
connections.add(websocket) |
| 12 |
|
| 13 |
try: |
| 14 |
async for message in websocket: |
| 15 |
print(message) |
| 16 |
|
| 17 |
for ws in connections: |
| 18 |
if ws != websocket: |
| 19 |
await ws.send(message) |
| 20 |
except: |
| 21 |
raise |
| 22 |
finally: |
| 23 |
connections.remove(websocket) |
| 24 |
|
| 25 |
|
| 26 |
asyncio.get_event_loop().run_until_complete( |
| 27 |
websockets.serve(echo, 'localhost', 8080)) |
| 28 |
asyncio.get_event_loop().run_forever() |