Skip to content

Instantly share code, notes, and snippets.

@jbutko
Created April 5, 2017 18:18
Show Gist options
  • Save jbutko/35273666c40a04ec3dee1f32c37cbe37 to your computer and use it in GitHub Desktop.
Save jbutko/35273666c40a04ec3dee1f32c37cbe37 to your computer and use it in GitHub Desktop.
Socket.io: broadcasting to (not only) rooms

Send to the sender and noone else

socket.emit('hello', msg);

Send to everyone including the sender(if the sender is in the room) in the room "my room"

io.to('my room').emit('hello', msg);

Send to everyone except the sender(if the sender is in the room) in the room "my room"

socket.broadcast.to('my room').emit('hello', msg);

Send to everyone in every room, including the sender

io.emit('hello', msg); // short version io.sockets.emit('hello', msg);

Send to specific socket only (private chat)

socket.broadcast.to(otherSocket.id).emit('hello', msg);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment