0

I'm new to socket.io and have caught up with the basic connections. But I would like to know how to send different notifications to different users. For example there are users 1 to 4 and category A to D. Each user might be subscribed to different catergories. See the table below

USER   | CATEGORY
1      | A
2      | A
4      | A
2      | B
4      | B
1      | C
2      | C
3      | C
4      | C
3      | D
4      | D

So if any new posts are added to any category, all the subscribed users should get respective notification. I know this may sounds silly, but I'm really confused that whether I need to create rooms with category ID and how to join all subscribed users to that rooms and so.

Any helps would be greatful. Thanks.

Sanju
  • 11
  • 1
  • 3
  • You have to filter out socker which belongs to user need to be notified. Same question ask in here as well https://stackoverflow.com/questions/26297373/send-update-notification-to-particular-users-using-socket-io – kamprasad Nov 06 '19 at 09:29

1 Answers1

0

If you wish to avoid using individual rooms you can just keep track of the connections yourself. You can do something like this

var clients = [];
io.sockets.on('connection', function(socket) {
   clients.push({     //Store information on the client when they connect
      id: socket.id,
      conn: socket,
      category: []
   });
   socket.on('disconnect', function() {
      clients = clients.filter(client => client.id != socket.id);  //Remove the disconnecting client
   });
});

Then once you have that setup whenever you want to update a category you can do this:

function updateCat(categoryName, updateData){
   clients.forEach(client => {
      if(client.category.includes(categoryName)){   //Check if the client is subscribed
         client.conn.emit('category_update', updateData);
      }
   });
}

This is a possible solution over using rooms, if you have any questions lemme know.

Strike Eagle
  • 852
  • 5
  • 19