1

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 multiple connections so I have to pair socketID (of each connection) and userID somehow. I has thinking about using redis to store userID->sessionID pairs. However, when user disconnects I need to remove that pair from redis.. but I have only socketID not userID so I can't select by that key..

Now, am I approaching this the wrong way or should I store both userID->socketID and socketID->userID pairs? Maybe someone could offer more elegant solution?

Audrius
  • 17
  • 5

1 Answers1

3

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);
    }
  });
alessioalex
  • 62,577
  • 16
  • 155
  • 122