How to send event only to the clients that are subscribed to it? #4816
-
Is there some common pattern how to send event only to the clients that are interested/subscribed to that event? I would like to avoid sending event to absolutely everyone who's connected to WS server. Example: Let's say there is a // Server
io.emit('todo.updated', { ...});
// Client
if (modalOpen) {
socket.on('todo.updated', () => {...});
} Right now, on the client, the event is simply not picked up by any code, and that works. But I was thinking if there is a way to not even send the event in case the client is not subscribed to it, to save some resources and bandwidth. Thank you 🙏🏽 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi! You are right, by default the events are received even if there is no registered handler. A subscription model is fairly straightforward to implement though:
const subscriptions = [];
function subscribe(topic) {
subscriptions.push(topic);
if (socket.connected) {
socket.emit("subscribe", [topic]);
}
}
// restore subscriptions upon reconnection
socket.on("connect", () => {
if (subscriptions.length) {
socket.emit("subscribe", subscriptions);
}
});
io.on("connection", (socket) => {
socket.on("subscribe", (topics) => {
socket.join(topics);
});
// send an event only to interested clients
io.to("todo.updated").emit("todo.updated", { ... });
}); |
Beta Was this translation helpful? Give feedback.
Hi! You are right, by default the events are received even if there is no registered handler.
A subscription model is fairly straightforward to implement though: