Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending message to a specific ID in Socket.IO 1.0

In socket.io 1.0 they provide a better way for this. Each socket automatically joins a default room by self id. Check documents: http://socket.io/docs/rooms-and-namespaces/#default-room

So you can emit to a socket by id with following code:

io.to(socketid).emit('message', 'for your eyes only');

In socket.io 1.0 you can do that with following code:

if (io.sockets.connected[socketid]) {
    io.sockets.connected[socketid].emit('message', 'for your eyes only');
}

Update:

@MustafaDokumacı's answer contains a better solution.


@Mustafa Dokumacı and @Curious already provided enough information, I am adding how you can get socket id.

To get socket id use socket.id:

var chat = io.of("/socket").on('connection',onSocketConnected);

function onSocketConnected(socket){
   console.log("connected :"+socket.id);  
}

If you have used a namespace I found that the following works :

//Defining the namespace <br>
var nsp = io.of('/my-namespace');

//targeting the message to socket id <br>
nsp.to(socket id of the intended recipient).emit('private message', 'hello');

More about namespaces: http://socket.io/docs/rooms-and-namespaces/


I believe both @Curious and @MustafaDokumacı provided solutions that work well. The difference though is that with @MustafaDokumacı's solution the message is broadcasted to a room and not only to a particular client.

The difference is prominent when an acknowledgement is requested.

io.sockets.connected[socketid].emit('message', 'for your eyes only', function(data) {...});

works as expected, while

io.to(socketid).emit('message', 'for your eyes only', function(data) {...});

fails with

Error: Callbacks are not supported when broadcasting