繁体   English   中英

带有 Socket.io 的通知 - 如何发送给特定用户/收件人?

[英]Notifications with Socket.io - how to emit to a specific user/recipient?

我想实现一个简单的通知系统。 user1喜欢user2的帖子时, user2应该会收到来自user1的实时通知。

这是客户端 function(Redux 操作)的一部分,其中有人喜欢一个帖子:

.then(() => {
  const socket = require("socket.io-client")(
    "http://localhost:5000"
  );
  socket.emit("like", user, post);
});

这是服务器套接字user1 ,在用户 1 喜欢用户user2的帖子后创建通知:

io.on("connection", (socket) => {
    socket.on("like", async (user, post) => {
        if (!post.post.likedBy.includes(user.user._id)) {
            const Notification = require("./models/Notification");

            let newNotification = new Notification({
                notification: `${user.user.username} liked your post!`,
                sender: user.user._id,
                recipient: post.post.by._id,
                read: false,
            });

            await newNotification.save();

            io.emit("notification");
        }
    });
});

这是创建通知后的客户端 function:

socket.on("notification", () => {
        console.log("liked");
});

现在的问题是console.log('liked')出现在user1user2上。 我怎样才能只发送给收到通知的用户 socket.io 如何找到收到user1通知的特定user2

您应该像这样存储所有用户的列表(数组或对象):

(请注意,当用户connectsleaves套接字服务器时,列表必须更新)

// an example of structure in order to store the users
const users = [
  {
    id: 1,
    socket: socket
  },
  // ...
];

然后你可以定位帖子所有者并向他发送这样的通知:

// assuming the the 'post' object contains the id of the owner
const user = users.find(user => user.id == post.user.id);
// (or depending of the storage structure) 
// const user = users[post.user.id]
user.socket.emit('notification');

这里有一个例子:

const withObject = {};
const withArray = [];

io.on('connection', socket => {
  const user = { socket : socket };
  socket.on('data', id => {
    // here you do as you want, if you want to store just their socket or another data, in this example I store their id and socket
    user.id = id;
    withObject[id] = user;
    withArray[id] = user;
    // or withArray.push(user);
  });

  socket.on('disconnect', () => {
    delete withObject[user.id];
    delete withArray[user.id];
    // or let index = users.indexOf(user);
    // if(index !=== -1) users.splice(index, 1);

  });
});

有很多方法可以实现我要解释的内容,但主要思想是将套接字与其他索引(例如用户 ID)链接起来,以便稍后在代码中检索它。

暂无
暂无

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

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