271

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 client-side or is there an easier way?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
switz
  • 24,384
  • 25
  • 76
  • 101

12 Answers12

966

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');

// list socketid
for (var socketid in io.sockets.sockets) {}
 OR
Object.keys(io.sockets.sockets).forEach((socketid) => {});
LearnRPG
  • 9,807
  • 1
  • 13
  • 7
  • 15
    Would you like to contribute this to [the FAQ](https://github.com/LearnBoost/socket.io/wiki)? or can I do it for you? (I'd provide a backlink here) – Kos Oct 18 '12 at 13:38
  • // sending to all clients in 'game' room(channel), include sender io.sockets.in('game').emit('message', 'cool game'); can we send the message excluding sender in this? – Thirumalai murugan Dec 07 '13 at 12:40
  • 1
    i dont' have an `io` here.only `socket` – chovy Dec 08 '13 at 00:46
  • 2
    In complement to `// sending to all clients except sender`, what to use for `// sending a response to sender client only` ? – Basj Dec 10 '14 at 11:27
  • 4
    Could you please add that according to [socket#in](http://socket.io/docs/server-api/#socket#in(room:string):socket), `socket.to('others').emit('an event', { some: 'data' });` also **broadcasts** in a room. – gongzhitaao May 22 '15 at 21:47
  • 144
    This is more useful than everything on the socket.io docs combined – Jonathan. Jun 09 '15 at 12:29
  • Awesome! How do you get `socketid` for sending to an individual socket? – Crashalot Aug 20 '15 at 01:23
  • I'd like to add something as per my experience. It appears that when you use socket.broadcast.emit('message', "this is a test"); it will only broadcast to the room that person is in. Is this true? – tylerism Sep 30 '15 at 19:07
  • 1
    Are there any docs for this? i can't find it on socket.io's official site. – Ole Henrik Skogstrøm Oct 11 '15 at 20:24
  • @Crashalot you can get to "socketid" by doing "socket.id". – Henry Zou Feb 03 '16 at 19:00
  • Is there a way to broadcast to an specific socket from io (no access to socket)? – Henry Zou Feb 03 '16 at 19:00
  • 1
    I figured it out. This is how to send to a specific user from IO: io.sockets.to(toSocket.id).emit('message', 'message to specific user'); – Henry Zou Feb 03 '16 at 19:13
  • Thanks for the list, the documentation is a bit vague – ka_lin Apr 08 '16 at 08:42
  • @tylerism I know your comment is posted nearly 10 months before, but I have tested it and `socket.broadcast.emit(event, message)` will broadcast to every clients no matter which room the sender or the client is in. – Calvin Lau Jul 06 '16 at 19:41
  • Sorry I realized what I meant was namespaces. – tylerism Jul 07 '16 at 02:46
  • @Sébastien Thanks for updating. Is my understanding correct that all of these codes are executed on the server-side and the client-side just simply "socket.emit"? – Woppi Sep 13 '16 at 11:23
  • To send to a specific client outside io.sockets.on(), ou can use : `io.sockets.connected[socket.id].emit('messages', str);` – Arthur Lacoste May 04 '17 at 14:24
  • // sending to all clients except sender socket.broadcast.emit('message', "this is a test"); - Doesn't work! – Ярослав Гойса Aug 08 '18 at 11:24
  • How to do same thing using socket.io version 2.0? – Rehan Apr 10 '20 at 19:34
  • Here are the links to the official cheatsheet which should be up to date everytime: website: https://socket.io/docs/emit-cheatsheet/ github: https://github.com/socketio/socket.io-website/blob/master/source/docs/emit-cheatsheet.md – robertgr991 May 11 '20 at 22:03
  • is 'message' here a keyword ? or could be changed ? – Qbik Feb 09 '21 at 22:00
46

From the @LearnRPG answer but with 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 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
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

To answer @Crashalot comment, socketid comes from:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })
soyuka
  • 8,839
  • 3
  • 39
  • 54
13

Here is a more complete answer about what has changed from 0.9.x to 1.x.

 // send to current request socket client
 socket.emit('message', "this is a test");// Hasn't changed

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); // Old way, still compatible
 io.emit('message', 'this is a test');// New way, works only in 1.x

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

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

 // sending to all clients in 'game' room(channel), include sender
 io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
 io.in('game').emit('message', 'cool game');// New way
 io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/

 // sending to individual socketid, socketid is like a room
 io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way

I wanted to edit the post of @soyuka but my edit was rejected by peer-review.

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
8

Emit cheatsheet

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

};
Community
  • 1
  • 1
7

broadcast.emit sends the msg to all other clients (except for the sender)

socket.on('cursor', function(data) {
  socket.broadcast.emit('msg', data);
});
Steel Brain
  • 4,321
  • 28
  • 38
Khaled Jouda
  • 293
  • 3
  • 8
4

For namespaces within rooms looping the list of clients in a room (similar to Nav's answer) is one of only two approaches I've found that will work. The other is to use exclude. E.G.

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}
gopi1410
  • 6,567
  • 9
  • 41
  • 75
runspired
  • 2,642
  • 1
  • 19
  • 24
3

Server-side all valid emit events list in V4.x

io.on("connection", (socket) => {

// basic emit
socket.emit(/* ... */);

// to all clients in the current namespace except the sender
socket.broadcast.emit(/* ... */);

// to all clients in room1 except the sender
socket.to("room1").emit(/* ... */);

// to all clients in room1 and/or room2 except the sender
socket.to(["room1", "room2"]).emit(/* ... */);

// to all clients in room1
io.in("room1").emit(/* ... */);

// to all clients in room1 and/or room2 except those in room3
io.to(["room1", "room2"]).except("room3").emit(/* ... */);

// to all clients in namespace "myNamespace"
io.of("myNamespace").emit(/* ... */);

// to all clients in room1 in namespace "myNamespace"
io.of("myNamespace").to("room1").emit(/* ... */);

// to individual socketid (private message)
io.to(socketId).emit(/* ... */);

// to all clients on this node (when using multiple nodes)
io.local.emit(/* ... */);

// to all connected clients
io.emit(/* ... */);

// WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
// named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

// with acknowledgement
socket.emit("question", (answer) => {
    // ...
});

// without compression
socket.compress(false).emit(/* ... */);

// a message that might be dropped if the low-level transport is not writable
socket.volatile.emit(/* ... */);

});

Client-side

// basic emit
    socket.emit(/* ... */);

// with acknowledgement
    socket.emit("question", (answer) => {
        // ...
    });

// without compression
    socket.compress(false).emit(/* ... */);

// a message that might be dropped if the low-level transport is not writable
    socket.volatile.emit(/* ... */);

archived link to source => http://archive.today/2021.06.22-023900/https://socket.io/docs/v4/emit-cheatsheet/index.html

Stephen
  • 415
  • 7
  • 8
1

Other cases

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};
1

Updated the list for further documentation.

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

Hope this helps.

Kent Aguilar
  • 5,048
  • 1
  • 33
  • 20
1

Updated for Socket.io v4.0.0+

To emit to all clients except sender in v4, you use:

socket.broadcast.emit(/* ... */);

Example Usage

io.on("connection", (socket) => {
   socket.on("message", (message) => {
      //sends "newMessage" to all sockets except sender
      socket.broadcast.emit("newMessage", message)
   })
})
Coder Gautam YT
  • 1,044
  • 7
  • 20
0

use this coding

io.sockets.on('connection', function (socket) {

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

        socket.broadcast.emit('moving', data);
    });

this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting

Abi
  • 65
  • 1
  • 6
0

I am using namespaces and rooms - I found

socket.broadcast.to('room1').emit('event', 'hi');

to work where

namespace.broadcast.to('room1').emit('event', 'hi');

did not

(should anyone else face that problem)

reabow
  • 219
  • 1
  • 6
  • 18