简体   繁体   English

如何使用 socket.io 向不同的用户发送不同的通知

[英]How to send different notifications to different users using socket.io

I'm new to socket.io and have caught up with the basic connections.我是 socket.io 的新手,并且已经掌握了基本连接。 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 .例如有用户 14类别 AD 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.我知道这可能听起来很傻,但我真的很困惑我是否需要创建具有类别 ID 的房间以及如何将所有订阅用户加入该房间等等。

Any helps would be greatful.任何帮助都会很棒。 Thanks.谢谢。

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.如果您有任何问题,请让我知道,这是使用房间的可能解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM