Harry .Naeem
Harry .Naeem

Reputation: 1301

How to send events/messages to specific clients in node.js using Socket.io?

i'm working on a Node.js app in which we are using socket.io for sending and receiving events/messages to clients. Initially it is sending events to clients using the following statement.

io.sockets.emit('SequenceLoad', data);

But now i want to send events only to specific clients using client specific sockets. I have searched alot regarding this, found some ways but none of them seems to work, found on various SO posts.

Here is the code that i have tried:

const io = require('socket.io')(http);
var socketsCollection = [];
io.on('connection', function (socket) {

  //Saving socket id's for sending events to specific sockets based on their ids
  socketsCollection.push(socket.id);
  socket.on('SequenceLoadServer', function (data) {
     // logger.info('Socket Server | Event: sequenceLoadServer with socket server. \n Data:'+ data);
     console.log("In APP.js for SequenceLoadServer event");
     console.log("Socket Id :" + socket.id);
     var socketId = null;
     setTimeout(function () {
        for (var item of socketsCollection) {
           if(item == socket.id){
              socketId= item;
              break;   
           }
        }
        console.log("Socket after searching Id :" + socketId);
        io.sockets.emit('SequenceLoad', data);   -> This works at the moment

        //Tried the following ways as well but none of them worked 

        //io.sockets.connected[socketId].emit('SequenceLoad', data);
        //io.sockets.socket(socketId).emit('SequenceLoad', data); 
        //io.to(socketId).emit('SequenceLoad', data);
        //io.to('/#' + socketId).emit('SequenceLoad', data);
        //io.to(`${socketId}`).emit('SequenceLoad', data);

     }, 1000 * 3);

  });
}

Version of socket.io in my project:

"socket.io": "^2.2.0",
"socket.io-client": "^2.2.0"

Any help would great, correct me if i'm doing wrong because i'm new to it. Thanks

Upvotes: 0

Views: 464

Answers (1)

James
James

Reputation: 82096

Given you have the socket instance, you can send to a specific client directly by:

io.to(`${socket.id}`).emit(...);

See Emit cheatsheet

Upvotes: 1

Related Questions