gpt4 book ai didi

node.js - Socket.io 实时聊天——管理用户好友

转载 作者:行者123 更新时间:2023-12-03 12:02:15 25 4
gpt4 key购买 nike

我正在用 React/Redux、Node (Express)、Socket.io 和 MySql 开发一个实时聊天应用程序。我想做的是没有“公共(public)”房间的实时聊天。它适用于用户之间的友谊/关系(与另一个用户是 friend 的用户可以一对一聊天)并且还处理组创建(用户可以创建一个与他想要的许多其他用户的组)。
一切正常,唯一的问题是我不确定获取每个用户的 friend /群组列表(也显示在线/离线状态)的最佳方法。
我目前的做法如下:

  • 每个连接的用户都存储在后端的一个对象中(带有他们的套接字 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 的用户有 friend 关系(因此可以与他们聊天)。而 ID = 2 的用户与 ID 为 1 的用户是 friend , 5、9 和 12。
    我会像这样跟踪每一个友谊,以便能够为每个用户发送正确的 friend 列表。我发现这种方法目前最方便,因为在更新的情况下(假设用户添加了 friend 或有人登录并且我必须向用户发送他正确更新的 friend 列表),发送会很痛苦正确的 friend 列表给正确的用户。或者也许我错过了什么?
    当用户连接并将他的 friend 列表从后端发送到前端时的代码如下所示:
  • 前端:
  • 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}`);
    }
    });
    如果这不是很清楚,我很抱歉,代码已经加载得很好了。我尽力解释正在发生的事情,但如果不清楚,请随时告诉我详细说明(另外,英语不是我的母语,使它变得更加困难)。
    我对这段代码的担忧是:

  • 是否可以将每个用户的每个友谊关系存储在“全局”对象 (userFriendsObject) 中?我很担心,因为如果我有 100 个连接的用户,每个用户有 20 个 friend ,那么对象会很大(最少 2000 个键/值,嵌套 2 层深)。更不用说它应该随着应用程序的使用而呈指数增长。


  • 什么是不将所有这些友谊关系存储在一个对象中的替代方法,但仍然能够以有效且可扩展的替代方法让每个用户的 friend 列表“在手边”?


  • 在代码的以下部分(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 });
    }
    }

  • 可以像我所做的那样在循环中向用户(可能是很多用户)发射吗?如果没有,我如何确保为给定用户发送正确的更新好友列表? (我想答案与我的其他问题有关)。


  • 我应该使用某种类型的存储,例如 indexedDB 吗?


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

    最佳答案

    我终于成功了。
    我通过使用 Redis 缓存存储来做到这一点。
    我所做的是,当我为每个用户获取每个 friend 和组时,我会在 Redis 存储中创建一个位置来存储它。然后我可以得到任何具有用户 ID 的用户 friend 。

    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#

    关于node.js - Socket.io 实时聊天——管理用户好友,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64215351/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com