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

标签 javascript node.js reactjs sockets socket.io

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

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

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

这是在 user1 喜欢 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");
        }
    });
});

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

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

现在的问题是 console.log('liked') 出现在 user1user2 上。我如何才能仅向收到通知的用户发送消息? socket.io 如何找到从 user1 接收通知的特定 user2

最佳答案

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

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

// 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)链接起来,以便稍后在代码中检索它。

关于javascript - 使用 Socket.io 的通知 - 如何发送给特定的用户/收件人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63152197/

相关文章:

Node.js Kue worker 发送结果

reactjs - 如何设置 react-admin Datagrid 标题的样式?

javascript - Jquery删除类并在单击的元素上添加类

javascript - 为什么这个 Angular 2 Pipe 不返回数据?

javascript - 如何在 Typescript 中编写文字 Javascript

node.js - ES6 类函数中导入模块

javascript - NodeJs : can't write a file

css - 使用 Styled Components 为什么伪类似乎仍然可以在没有&符号的情况下工作?

javascript - 如何使用 API 数据正确更新 React 和 Chart.js 应用程序中的图表

javascript - Tampermonkey,Chrome,如何将html实体改回符号?