我想实现一个简单的通知系统。当 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')
出现在 user1
和 user2
上。我如何才能仅向收到通知的用户发送消息? 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/