Emitting events

There are several ways to send events between the server and the client.

Basic emit

The Socket.IO API is inspired from the Node.js EventEmitter, which means you can emit events on one side and register listeners on the other:

  1. // server-side
  2. io.on("connection", (socket) => {
  3. socket.emit("hello", "world");
  4. });
  5. // client-side
  6. socket.on("hello", (arg) => {
  7. console.log(arg); // world
  8. });

This also works in the other direction:

  1. // server-side
  2. io.on("connection", (socket) => {
  3. socket.on("hello", (arg) => {
  4. console.log(arg); // world
  5. });
  6. });
  7. // client-side
  8. socket.emit("hello", "world");

You can send any number of arguments, and all serializable data structures are supported, including binary objects like Buffer or TypedArray.

  1. // server-side
  2. io.on("connection", (socket) => {
  3. socket.emit("hello", 1, "2", { 3: '4', 5: Buffer.from([6]) });
  4. });
  5. // client-side
  6. socket.on("hello", (arg1, arg2, arg3) => {
  7. console.log(arg1); // 1
  8. console.log(arg2); // "2"
  9. console.log(arg3); // { 3: '4', 5: ArrayBuffer (1) [ 6 ] }
  10. });

There is no need to run JSON.stringify() on objects as it will be done for you.

  1. // BAD
  2. socket.emit("hello", JSON.stringify({ name: "John" }));
  3. // GOOD
  4. socket.emit("hello", { name: "John" });

Note: Map and Set are not serializable and must be manually serialized:

  1. const serializedMap = [...myMap.entries()];
  2. const serializedSet = [...mySet.keys()];

Acknowledgements

Events are great, but in some cases you may want a more classic request-response API. In Socket.IO, this feature is named acknowledgements.

You can add a callback as the last argument of the emit(), and this callback will be called once the other side acknowledges the event:

  1. // server-side
  2. io.on("connection", (socket) => {
  3. socket.on("update item", (arg1, arg2, callback) => {
  4. console.log(arg1); // 1
  5. console.log(arg2); // { name: "updated" }
  6. callback({
  7. status: "ok"
  8. });
  9. });
  10. });
  11. // client-side
  12. socket.emit("update item", "1", { name: "updated" }, (response) => {
  13. console.log(response.status); // ok
  14. });

Timeout are not supported by default, but it is quite straightforward to implement:

  1. const withTimeout = (onSuccess, onTimeout, timeout) => {
  2. let called = false;
  3. const timer = setTimeout(() => {
  4. if (called) return;
  5. called = true;
  6. onTimeout();
  7. }, timeout);
  8. return (...args) => {
  9. if (called) return;
  10. called = true;
  11. clearTimeout(timer);
  12. onSuccess.apply(this, args);
  13. }
  14. }
  15. socket.emit("hello", 1, 2, withTimeout(() => {
  16. console.log("success!");
  17. }, () => {
  18. console.log("timeout!");
  19. }, 1000));

Volatile events

Volatile events are events that will not be sent if the underlying connection is not ready (a bit like UDP, in terms of reliability).

This can be interesting for example if you need to send the position of the characters in an online game (as only the latest values are useful).

  1. socket.volatile.emit("hello", "might or might not be received");

Another use case is to discard events when the client is not connected (by default, the events are buffered until reconnection).

Example:

  1. // server-side
  2. io.on("connection", (socket) => {
  3. console.log("connect");
  4. socket.on("ping", (count) => {
  5. console.log(count);
  6. });
  7. });
  8. // client-side
  9. let count = 0;
  10. setInterval(() => {
  11. socket.volatile.emit("ping", ++count);
  12. }, 1000);

If you restart the server, you will see in the console:

  1. connect
  2. 1
  3. 2
  4. 3
  5. 4
  6. # the server is restarted, the client automatically reconnects
  7. connect
  8. 9
  9. 10
  10. 11

Without the volatile flag, you would see:

  1. connect
  2. 1
  3. 2
  4. 3
  5. 4
  6. # the server is restarted, the client automatically reconnects and sends its buffered events
  7. connect
  8. 5
  9. 6
  10. 7
  11. 8
  12. 9
  13. 10
  14. 11