Skip to content

How to send event only to the clients that are subscribed to it? #4816

Discussion options

You must be logged in to vote

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:

  • client side:
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);
  }
});
  • server side:
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", {

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@ondrejsevcik
Comment options

@darrachequesne
Comment options

Answer selected by ondrejsevcik
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants