Emitting events
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:
This also works in the other direction:
You can send any number of arguments, and all serializable datastructures are supported, including binary objects like or TypedArray.
// server-side
io.on("connection", (socket) => {
socket.emit("hello", 1, "2", { 3: '4', 5: Buffer.from([6]) });
});
// client-side
socket.on("hello", (arg1, arg2, arg3) => {
console.log(arg1); // 1
console.log(arg2); // "2"
console.log(arg3); // { 3: '4', 5: ArrayBuffer (1) [ 6 ] }
});
There is no need to run JSON.stringify()
on objects as it will be done for you.
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:
// server-side
io.on("connection", (socket) => {
socket.on("update item", (arg1, arg2, callback) => {
console.log(arg1); // 1
console.log(arg2); // { name: "updated" }
callback({
status: "ok"
});
});
});
// client-side
socket.emit("update item", "1", { name: "updated" }, (response) => {
console.log(response.status); // ok
});
Timeout are not supported by default, but it is quite straightforward to implement:
Volatile events are events that will not be sent if the underlying connection is not ready (a bit like , in terms of reliability).
Another use case is to discard events when the client is not connected (by default, the events are buffered until reconnection).
Example:
If you restart the server, you will see in the console:
Without the volatile
flag, you would see: