2

So I'm trying to emit data from server to one specific client upon connecting (this is server code):

io.sockets.on('connection', function(socket){
   socket.id = Math.random();

   //this works, but sends data to all clients, which is not what I need
   socket.emit('serverMsg');

   //this seems to do nothing
   io.to(socket.id).emit('serverMsg');

   //this also does nothing
   socket.broadcast.to(socket.id).emit('serverMsg');
});

As I've commented the lines, I can emit data to all clients, but nothing happens when I try to emit to specific client with socket.id. What am I doing wrong? There are no error messages or anything.

  • Possible duplicate of [Sending message to specific client in Socket IO](https://stackoverflow.com/questions/35680565/sending-message-to-specific-client-in-socket-io) – Romeo Sierra May 27 '18 at 11:31

2 Answers2

1

When a client connects, its socket.id is automatically initialized. Also, it joins a room with the same name:

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.

If, for some reason, you wish to redefine the id, you would need to assign the socket to the corresponding room as well, since the to( ) method expects as its argument the name of the room of interest. In the code in your post, you redefine the id, but the association with the corresponding room is not established, thus the emit method emits the data into the "void" (into a room the name of which is equal to the result of Math.random(), but which contains no sockets)...

const customId = ....
socket.id = customId;

socket.join(customId);

io.to(customId).emit(...)
ewcz
  • 12,819
  • 1
  • 25
  • 47
0

this work for me

const http = require('http').createServer();
const sio = require('socket.io')(http);

var port = xxxx;
var ip = "xxx.xxx.x.x";

sio.on('connection', async function(socket) {
     sio.sockets.to(socket.id).emit("from_server", "your are connected"); 
});



http.listen(port, ip, function() {
    console.log('Server active. listening on :' + ip + ":" + port);
});
mamena tech
  • 496
  • 5
  • 16