Socket.io - transfer to specific users

I need to create twosome chat using websockets (socket.io + node.js). So, a simple example for broadcasting to all users:

socket.on('user message', function (msg) {
    socket.broadcast.emit('user message', socket.nickname, msg);
  });

But how can I broadcast it from a specific user to a specific user?

+5
source share
1 answer

There are two possibilities:

1) Each socket has its own unique identifier stored in socket.id. If you know the identifier of both users, you can simply use

io.sockets[id].emit(...)

2) Define your own identifier (e.g. username) and use

socket.join('priv/John');

connection. , John,

socket.broadcast.to('priv/John').emit(...)

: , .

+13

All Articles