簡體   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