Skip to content

Instantly share code, notes, and snippets.

@Kenny2github
Last active February 11, 2019 09:52
Show Gist options
  • Select an option

  • Save Kenny2github/21dfc2cbf971c7fd1b028aca62d0dd7a to your computer and use it in GitHub Desktop.

Select an option

Save Kenny2github/21dfc2cbf971c7fd1b028aca62d0dd7a to your computer and use it in GitHub Desktop.
Forward a message sent by one client to the rest of the clients. Messages sent from clients using one path are not forwarded to other paths. Requires the `websockets` Python library.
from __future__ import print_function
import asyncio
from sys import argv
import websockets
connected = {}
def handler(sock, path):
if path not in connected:
connected[path] = set()
connected[path].add(sock)
print('Connected:', id(sock))
try:
while 1:
data = await sock.recv()
print(id(sock), ':', data)
for s in connected[path]:
await s.send(data)
except (websockets.ConnectionClosed, KeyboardInterrupt):
print('Disconnecting:', id(sock))
return
finally:
connected[path].remove(sock)
port = 5678 if len(argv) < 1 else int(argv[1])
loop = asyncio.get_event_loop()
print('Serving 0.0.0.0 on port', port)
loop.run_until_complete(websockets.serve(handler, '0.0.0.0', port))
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment