Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js socket.io How to emit to a particular client?

Tags:

I want to "emit" a message to a particular client which is selected based on another message received in a different client, How do I do this?

I am thinking of joining each client to their own "room" and then broadcast. Is there a better way?

like image 736
srinathhs Avatar asked Apr 11 '12 16:04

srinathhs


People also ask

How do I connect socket.io to client side?

var socket = require('socket. io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket. on('connect', function() { console. log("Successfully connected!"); });

How do I send a message to a socket?

The send() function initiates transmission of a message from the specified socket to its peer. The send() function sends a message only when the socket is connected (including when the peer of the connectionless socket has been set via connect()). The length of the message to be sent is specified by the len argument.


2 Answers

UPDATE for socket.io version 1.0 and above

io.to(socketid).emit('message', 'whatever'); 

For older version:

You can store each client in an object as a property. Then you can lookup the socket based on the message:

var basket = {};  io.sockets.on('connection', function (socket) {   socket.on("register", function(data) {     basket[data.nickname] = socket.id;   });   socket.on("privmessage", function(data){     var to = basket[data.to];     io.sockets.socket(to).emit(data.msg);   }); }); 

Not tested...but it should give you an idea

like image 79
Francesco Laurita Avatar answered Oct 07 '22 04:10

Francesco Laurita


For socket.io version 1.0 use:

io.to(socketid).emit('message', 'whatever'); 
like image 40
Minho Yi Avatar answered Oct 07 '22 02:10

Minho Yi