switz switz - 1 year ago 297
Javascript Question

Send response to all clients except sender (Socket.io)

To send something to all clients, you use:

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

To receive from clients, you use:

socket.on('cursor', function(data) {

How can I combine the two so that when recieving a message on the server from a client, I send that message to all users except the one sending the message.

socket.on('cursor', function(data) {
io.sockets.emit('response', data);

Do I have to hack it around by sending the client-id with the message and then checking on the clientside or is there an easier way?

Answer Source

Here is my list (updated for 1.0):

 // sending to sender-client only
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.emit('message', "this is a test");

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 io.in('game').emit('message', 'cool game');

 // sending to sender client, only if they are in 'game' room(channel)
 socket.to('game').emit('message', 'enjoy the game');

 // sending to all clients in namespace 'myNamespace', include sender
 io.of('myNamespace').emit('message', 'gg');

 // sending to individual socketid
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download