Emit cheatsheet

Server-side

  1. io.on("connection", (socket) => {
  2. // basic emit
  3. socket.emit(/* ... */);
  4. // to all clients in the current namespace except the sender
  5. socket.broadcast.emit(/* ... */);
  6. // to all clients in room1 except the sender
  7. socket.to("room1").emit(/* ... */);
  8. // to all clients in room1 and/or room2 except the sender
  9. socket.to("room1").to("room2").emit(/* ... */);
  10. // to all clients in room1
  11. io.in("room1").emit(/* ... */);
  12. // to all clients in namespace "myNamespace"
  13. io.of("myNamespace").emit(/* ... */);
  14. // to all clients in room1 in namespace "myNamespace"
  15. io.of("myNamespace").to("room1").emit(/* ... */);
  16. // to individual socketid (private message)
  17. io.to(socketId).emit(/* ... */);
  18. // to all clients on this node (when using multiple nodes)
  19. io.local.emit(/* ... */);
  20. // to all connected clients
  21. io.emit(/* ... */);
  22. // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  23. // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
  24. // with acknowledgement
  25. socket.emit("question", (answer) => {
  26. // ...
  27. });
  28. // without compression
  29. socket.compress(false).emit(/* ... */);
  30. // a message that might be dropped if the low-level transport is not writable
  31. socket.volatile.emit(/* ... */);
  32. });

Client-side

  1. // basic emit
  2. socket.emit(/* ... */);
  3. // with acknowledgement
  4. socket.emit("question", (answer) => {
  5. // ...
  6. });
  7. // without compression
  8. socket.compress(false).emit(/* ... */);
  9. // a message that might be dropped if the low-level transport is not writable
  10. socket.volatile.emit(/* ... */);

Reserved events

On each side, the following events are reserved and should not be used as event names by your application:

  • connect
  • connect_error
  • disconnect
  • disconnecting
  • newListener
  • removeListener
  1. // BAD, will throw an error
  2. socket.emit("disconnecting");