channel.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from typing import Dict
  2. from websockets.asyncio.server import ServerConnection
  3. from websockets.exceptions import ConnectionClosed
  4. class Subscriber:
  5. player_enabled = False
  6. ws: ServerConnection
  7. def __init__(self, ws):
  8. self.ws = ws
  9. class Channel:
  10. subscribers: Dict[ServerConnection, Subscriber]
  11. def __init__(self):
  12. self.subscribers = dict()
  13. def subscribe(self, ws: ServerConnection):
  14. if ws not in self.subscribers:
  15. self.subscribers[ws] = (Subscriber(ws))
  16. def unsubscribe(self, ws: ServerConnection):
  17. if ws in self.subscribers:
  18. self.subscribers.pop(ws)
  19. def get_player_enabled_subscribers(self):
  20. return filter(lambda s: s.player_enabled, self.subscribers.values())
  21. async def send(self, message):
  22. for sub in list(self.subscribers.values()):
  23. try:
  24. await sub.ws.send(message)
  25. except ConnectionClosed:
  26. self.unsubscribe(sub.ws)
  27. # else:
  28. # print("closed ws still in channel")
  29. # self.unsubscribe(sub.ws)