How to handle user and socket pairs with node.js + redis

后端 未结 1 1343
-上瘾入骨i
-上瘾入骨i 2021-02-11 08:25

Straight to the point: I am using node.js, socket.io and redis for a private chat system.

On connect user passes his website id (userID) to node.js server. He may have m

1条回答
  •  逝去的感伤
    2021-02-11 09:02

    A more elegant solution would be to make each socket connect to the channel userID, for example:

    io.sockets.on('connection', function (socket) {
      socket.join(userID);
    });
    
    // when you want somebody to send a message to userID you can do:
    io.sockets.in(userID).emit(message);
    

    There are two things you need to take care of here:

    1. Make sure that only userID can connect to his channel, thus verify the session ( read more here: http://www.danielbaulig.de/socket-ioexpress/ )
    2. On connection increase the value for userID in redis (so that you know a new connection for that user is listening) and on disconnect decrease the userID value (so that you know the number of connections still listening). If the value is 0 then you emit a message to the chat stating that userID has left (since the number of connections listening to the userID channel is 0).

    When other users will want to send a message to userID, they don't need to connect to the userID channel, they can send a message to the chat channel and pass userID as a property. For example:

    var chat = io
      .of('/chat')
      .on('connection', function (socket) {
        // connected to public chat
      })
      .on('message', function (data) {
        if (data.userID && data.message) {
          io.sockets.in(userID).emit('UserX: ' + data.message);
        }
      });
    

    0 讨论(0)
提交回复
热议问题