From ed498a292a2abb3dd4039182bb85875656e1c7d3 Mon Sep 17 00:00:00 2001 From: MingxuanGame Date: Sun, 27 Jul 2025 13:09:36 +0000 Subject: [PATCH] feat(signalr): support broadcast to group --- app/signalr/hub/hub.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/signalr/hub/hub.py b/app/signalr/hub/hub.py index 42c6aef..02c5537 100644 --- a/app/signalr/hub/hub.py +++ b/app/signalr/hub/hub.py @@ -38,6 +38,9 @@ class Client: self._ping_task: asyncio.Task | None = None self._store = ResultStore() + def __hash__(self) -> int: + return hash(self.connection_id + self.connection_token) + async def send_packet(self, packet: Packet): await self.connection.send_bytes(self.procotol.encode(packet)) @@ -65,10 +68,17 @@ class Hub: self.clients: dict[str, Client] = {} self.waited_clients: dict[str, int] = {} self.tasks: set[asyncio.Task] = set() + self.groups: dict[str, set[Client]] = {} def add_waited_client(self, connection_token: str, timestamp: int) -> None: self.waited_clients[connection_token] = timestamp + def get_client_by_id(self, id: str, default: Any = None) -> Client: + for client in self.clients.values(): + if client.connection_id == id: + return client + return default + def add_client( self, connection_id: str, @@ -112,6 +122,14 @@ class Hub: tasks.append(self.call_noblock(client, method, *args)) await asyncio.gather(*tasks) + async def broadcast_group_call( + self, group_id: str, method: str, *args: Any + ) -> None: + tasks = [] + for client in self.groups.get(group_id, []): + tasks.append(self.call_noblock(client, method, *args)) + await asyncio.gather(*tasks) + async def _listen_client(self, client: Client) -> None: jump = False while not jump: