Emit cheatsheet

  1. io.on('connection', onConnect);
  2. function onConnect(socket){
  3. // sending to the client
  4. socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
  5. // sending to all clients except sender
  6. socket.broadcast.emit('broadcast', 'hello friends!');
  7. // sending to all clients in 'game' room except sender
  8. socket.to('game').emit('nice game', "let's play a game");
  9. // sending to all clients in 'game1' and/or in 'game2' room, except sender
  10. socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
  11. // sending to all clients in 'game' room, including sender
  12. io.in('game').emit('big-announcement', 'the game will start soon');
  13. // sending to all clients in namespace 'myNamespace', including sender
  14. io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
  15. // sending to a specific room in a specific namespace, including sender
  16. io.of('myNamespace').to('room').emit('event', 'message');
  17. // sending to individual socketid (private message)
  18. io.to(socketId).emit('hey', 'I just met you');
  19. // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  20. // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
  21. // sending with acknowledgement
  22. socket.emit('question', 'do you think so?', function (answer) {});
  23. // sending without compression
  24. socket.compress(false).emit('uncompressed', "that's rough");
  25. // sending a message that might be dropped if the client is not ready to receive messages
  26. socket.volatile.emit('maybe', 'do you really need it?');
  27. // specifying whether the data to send has binary data
  28. socket.binary(false).emit('what', 'I have no binaries!');
  29. // sending to all clients on this node (when using multiple nodes)
  30. io.local.emit('hi', 'my lovely babies');
  31. // sending to all connected clients
  32. io.emit('an event sent to all connected clients');
  33. };

Note: The following events are reserved and should not be used as event names by your application:

  • connect
  • connection
  • connect_error
  • connect_timeout
  • error
  • disconnect
  • disconnecting
  • newListener
  • reconnect_attempt
  • reconnecting
  • reconnect_error
  • reconnect_failed
  • removeListener
  • ping
  • pong