【问题标题】:Socket.io live chat - managing user friendsSocket.io 实时聊天——管理用户好友
【发布时间】:2020-10-05 19:57:15
【问题描述】:

我正在用 React / Redux、Node (Express)、Socket.io 和 MySql 开发一个实时聊天应用程序。我想做的是没有“公共”房间的实时聊天。它适用于用户之间的友谊/关系(与另一个用户是朋友的用户可以一对一聊天),还可以处理群组创建(用户可以与他想要的任意数量的其他用户创建一个群组)。

一切正常,唯一的问题是我不确定获取每个用户的朋友/群组列表(也显示在线/离线状态)的最佳方法。

我目前的做法如下:

  • 每个连接的用户都存储在后端的一个对象中(带有他们的套接字 ID)。每个键是连接的用户 ID,值是它的套接字 ID。它看起来像这样:
let connectedUsers = {
    1: 'socketIdUser1'
    2: 'socketIdUser2',
    5: 'socketIdUser5',
    // ... And so on for every user that is connected
}

如果我们以上面的对象为例,我们知道 ID 为 1、2 和 5 的用户是连接的。

  • 然后,对于每个单独的连接用户,我将他们与其他人的友谊关系存储在另一个对象中,如下所示(我只存储 ID):
let userFriendsObject = {
    1: {
        2: 2,
        4: 4,
        5: 5,
    },
    2: {
        1: 1,
        5: 5,
        9: 9,
        12: 12,
    }
}

这个对象告诉我们,ID 为 1 的用户与 ID 为 2、4 和 5 的用户有好友关系(因此可以与他们聊天)。而 ID = 2 的用户与 ID 为好友的用户是好友是 1、5、9 和 12。

我会像这样跟踪每个朋友,以便能够为每个用户发送正确的朋友列表。我发现这种方法目前最方便,因为在更新的情况下(假设用户添加了朋友或有人登录并且我必须向用户发送他正确更新的朋友列表),发送会很痛苦正确的朋友列表给正确的用户。或者也许我错过了什么?

当用户连接并让他的朋友列表从后端发送到前端时的代码如下所示:

  • 前端:
useEffect(() => {

    /* When a user connects, this event is emited to the backend, which 
    will then emit back the below "set user friends list" event */

    socket.emit('new connected user', { id: currentUser.id, pseudo: currentUser.pseudo });


    // Listening emited event from the backend, holding the user's friend list

    socket.on('set user friends list', friendStack => {
        if (friendStack) {
            // dispatch hook to set the friend list in Redux global state
            dispatch(setFriendList(friendStack)); 
        }   
    });

    
    // Listening emited event from the backend, updates online status for newly connected user's friends

    socket.on('set friend status', ({ friendId, isActive }) => {
        dispatch(setOnline({ id: friendId, changes: { isActive } }));
    });

}, []);

  • 后端:
// "Global" object containing every connected user (key = user ID, value = socket ID)

let connectedUsers = {};

// "Global" object containing every user ID, themselves containing every friends IDs (= holding every friendships)

let userFriendsObject = {};

socket.on('new connected user', ({ userId, pseudo => {
    session.user = {
        id: userId,
        pseudo: pseudo,
        isActive: true,
    };
            

    connectedUsers[userId] = socket.id; // Used to know which users are connected
            
    session.save();


    /* I use EventEmitter() from the 'events' library to emit events 
    from the backend to the backend for everything DB related,
    to better split the code */ 
    
    eventEmitter.emit('get friends list', { userId });
            

    /* Function triggered below (after all the "sockets.on()",
    in eventEmitter.on('get friends list'), to process the 
    friend list received from the DB just above) */

    setFriendList = function(friends) {
        

         /* I emit to the newly connected user's socket his friend list */

         ioChat.to(socket.id).emit('set user friends list', friends[userId]);
                

        /* To update the online status ("isActive") of the friends side of the newly connected 
        user, I loop through connectedUser object keys (= connected users IDs) ... */

        for (let i in connectedUsers) {


            /* ... to compare it with the userFriendsObject key of the user to check
            (= his friend list), to know which of his friends are connected... */

            if (userFriendsObject[userId] && userFriendsObject[userId][i] === parseInt(i, 10) && parseInt(i, 10) !== userId) {

         
                /* ... and then send to his connected friends an event which will say 
                to them to update the status of the newly connected user */

                ioChat.to(connectedUsers[i]).emit('set friend status', { friendId: userId, isActive: true });
            }
        }
    };
});

// ...

eventEmitter.on('get friends list', async ({ userId }) => {
    try {
        // Setting the online status of the user in DB (1 = online, 0 = offline)

        await User.setUserStatus(userId, 1);


        // Calling the DB to get the user friends

        const friendList = await User.getUserFriendsData(userId);
        

        /* This variable will be "local" and hold all the user's friend list
        as a normalized object ready for Redux */
        
        let friends = {};

        
        // Loop through the friendList retrieved from the DB

        let i = 0, resultLength = friendList.length;
        for (i; i < resultLength; i++) {


            // Putting the "local" user's friend list in "friends" object   

            friends[userId] = {
                ...friends[userId],
                [friendList[i].userId]: {
                    id: friendList[i].userId,
                    pseudo: friendList[i].pseudo,
                    email: friendList[i].email,
                    createdOn: friendList[i].createdOn,
                    isActive: friendList[i].isActive !== 0,
                    roomId: friendList[i].roomId,
                }
            };


            /* Using userFriendsObject as a "global" object, holding every user's friend list
            (only the IDs though, as explained in the beginning of my post) */

            userFriendsObject[userId] = {
                ...userFriendsObject[userId],
                [friendList[i].userId]: friendList[i].userId,
            };
        }


            /* Here I call the setFriendList() function which is in 
            "socket.on('new connected user')" and is used 
            to process the friend list and emit events accordingly */

            setList(friends);
    }
    catch (error) { 
        console.error(`Error EE.on('get list') : ${error}`);
    }
});

很抱歉,如果这不是很清楚,代码已经很好地加载了。我已尽力解释正在发生的事情,但如果不清楚,请随时告诉我详细说明(另外,英语不是我的母语,使它变得更加困难)。

我对这段代码的担忧是:

    1. 是否可以将每个用户的每个友谊关系存储在一个“全局”对象 (userFriendsObject) 中?我很担心,因为如果我有 100 个连接的用户,每个用户有 20 个朋友,那么对象会很大(最少 2000 个键/值,嵌套 2 层深)。更不用说它会随着应用的使用呈指数级增长。
    1. 有什么替代方法可以不将所有这些友谊关系存储在一个对象中,但仍然能够让每个用户的朋友列表“在手边”,这是一种有效且可扩展的替代方法?

在以下部分代码中(setFriendList()函数,在socket.on('new connected user')中:

// Looping through the connectedUsers object...
for (let i in connectedUsers) {


    /* ... to compare it with the userFriendsObject key of the user to check
    (= his friend list), to know which of his friends are connected... */

    if (userFriendsObject[userId] && userFriendsObject[userId][i] === parseInt(i, 10) && parseInt(i, 10) !== userId) {

         
        /* ... and then send to his connected friends an event which will say 
        to them to update the status of the newly connected user */

        ioChat.to(connectedUsers[i]).emit('set friend status', { friendId: userId, isActive: true });
    }
}
    1. 是否可以像我所做的那样在循环中向用户(可能是很多用户)发射?如果没有,我如何确保为给定用户发送正确的更新好友列表? (我想答案与我的其他问题有关)。
    1. 我应该使用某种类型的存储,比如 indexedDB 吗?

我希望有人能够帮助我。我的代码有效,但我很确定它远非最佳性能。非常感谢您的时间和帮助。

【问题讨论】:

    标签: node.js express sockets socket.io


    【解决方案1】:

    我终于成功了。

    我是通过使用 Redis 缓存存储做到这一点的。

    我所做的是,当我为每个用户获取每个朋友和组时,我会在 Redis 存储中创建一个位置来存储它。然后,我可以使用该用户 ID 获取任何用户朋友。

    const redis = require('redis');
    const redisStore = redis.createClient();
    
    // I can then store a friend (friend being a JSON object) like so :
    redisStore.hset(`${userId}:friends`, friend.id, JSON.stringify(friend));
    
    // This way I store every friend as a key / value in ${userId}:friends
    // I can retrieve a specific friend by its ID like so :
    redisStore.hget(`${userId}:friends`, friendID, (err, result) => {
        // Here, the stringified friend object with ID = friendID is in result variable
    });
    
    // Or I can get all friends of user = userId like so :
    redisStore.hgetall(`${userId}:friends`, (err, results) => {
         // Here, every friends (stringified) of user with id = userId are in results variable
    }); 
    

    我刚开始使用 Redis,我发现它非常强大,非常适合我使用的那种应用程序。

    我不再需要使用“全局”对象,就像我以前用来存储用户的友谊关系(如“userFriendsObject”对象)。我可以在 Redis 中存储我想要的任何东西并快速取回。它在表演时也应该非常快。

    我还可以根据情况使用任何其他存储数据类型或技术。

    我找到了一个开始了解 Redis 的好地方:https://redis.io/topics/data-types-intro

    你可以在这里找到每个 Redis 命令:https://redis.io/commands#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 2020-01-18
      • 2018-01-03
      • 1970-01-01
      • 2014-01-12
      • 2022-10-14
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多