Dav*_*vid 3 javascript sockets node.js socket.io reactjs
我想实现一个简单的通知系统。当user1喜欢的user2帖子时,user2应该会收到来自的实时通知user1。
这是客户端功能(Redux 操作)的一部分,其中有人喜欢帖子:
.then(() => {
const socket = require("socket.io-client")(
"http://localhost:5000"
);
socket.emit("like", user, post);
});
Run Code Online (Sandbox Code Playgroud)
user1这是服务器套接字函数,在Likesuser2的帖子之后创建通知:
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");
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是创建通知后的客户端函数:
socket.on("notification", () => {
console.log("liked");
});
Run Code Online (Sandbox Code Playgroud)
现在的问题是和console.log('liked')都出现。我怎样才能只发送给收到通知的用户?socket.io 如何找到从 接收通知的特定对象?user1user2user2user1
您应该存储所有用户的列表(数组或对象),如下所示:
connects(请注意,当用户或leaves套接字服务器时该列表必须更新)
// an example of structure in order to store the users
const users = [
{
id: 1,
socket: socket
},
// ...
];
Run Code Online (Sandbox Code Playgroud)
然后您可以定位帖子所有者并向他发送如下通知:
// 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');
Run Code Online (Sandbox Code Playgroud)
这里有一个例子:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
有很多方法可以实现我想要解释的内容,但主要思想是将套接字与其他索引(例如用户 ID)链接起来,以便稍后在代码中检索它。
| 归档时间: |
|
| 查看次数: |
3952 次 |
| 最近记录: |