How can I utilize broadcaster to subscribe multiple channel? #48
Unanswered
vaibhavmule
asked this question in
Q&A
Replies: 3 comments 3 replies
-
Beta Was this translation helpful? Give feedback.
3 replies
-
I simply added a third handler like so @router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await run_until_first_complete(
(ws_receiver, {"ws": websocket}),
(ws_subscribe_all, {"ws": websocket}),
(ws_subscribe_private, {"ws": websocket, "user_profile_id": user_profile.id}),
)
async def ws_receiver(ws: WebSocket):
async for message in ws.iter_text():
# Handle message here
pass
async def ws_subscribe_private(ws: WebSocket, user_profile_id: int):
private_channel = f"{WS_CHANNEL_PRIVATE_KEY}:{user_profile_id}"
async with broadcast.subscribe(channel=private_channel) as subscriber:
async for event in subscriber:
await ws.send_text(event.message)
async def ws_subscribe_all(ws: WebSocket):
async with broadcast.subscribe(channel=WS_CHANNEL_ALL_KEY) as subscriber:
async for event in subscriber:
await ws.send_text(event.message) Of course this won't scale if you have a high number of channels, but for a broadcast and private channels, this works great. |
Beta Was this translation helpful? Give feedback.
0 replies
-
This definitely seems like something that should be more straightforward. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I know a way to have a dynamic channel by having chatroom id in URL,
/ws/{chat_id}
I want to send
{'type': 'subscribe', 'chat_id': 'dsfjkhdskjfhdskjhfkjdsahfa'}
how can i have multiple subscriber for same socket connection?
Beta Was this translation helpful? Give feedback.
All reactions