maroodb
maroodb

Reputation: 1108

How to get the socket object of each connected user in nodejs?



I am using socket.io to emit notification for users.

I have a listener that watch for an event.

 myEvent.watch ((res,err)=> {
      if (!err) {
        let id = res.userID;
        let msg = res.msg;
        //to implement
        sendMessage(id, msg);
   }
}

And I want to emit a message using socket.io to the concerned user. I am thinking about storing socket object in memory by userID;

io.on('connection', function (socket) { 
       // memoryStroage is a key-value sotrage.
        memoryStorage.put(socket.id, socket);
        socket.on('message', function (data) {
            console.log(data);
        });
    });

and then in the sendMessage service:

function sendMessage(id, msg) {
     let socket = memoryStroage.get(id);
     socket.emit('new-message', msg);
}

I want to is that a good way ?

Upvotes: 0

Views: 116

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40394

You should use socket.io rooms.

Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id.

So if you have the socket id, you can use:

function sendMessage(id, msg) {
   io.to(id).emit('new-message', msg);
}

You can use a custom user id too, using socket.join

io.on('connection', function(socket) {
    // memoryStroage is a key-value sotrage.
    const userId = getUserId(socket); // Get logged user Id somehow
    socket.join(`user-${userId}`);
    /* ... */
});

function sendMessage(id, msg) {
   io.to(`user-${id}`).emit('new-message', msg);
}

Upvotes: 1

Related Questions