Socket.IO makes it easy to send events to all the connected clients.
Please note that broadcasting is a server-only feature.
io.emit("hello", "world");
Clients that are currently disconnected (or in the process of reconnecting) won't receive the event. Storing this event somewhere (in a database, for example) is up to you, depending on your use case.
io.on("connection", (socket) => {
socket.broadcast.emit("hello", "world");
});
In the example above, using socket.emit("hello", "world") (without broadcast flag) would send the event to "client A". You can find the list of all the ways to send an event in the cheatsheet.
Broadcasting also works with multiple Socket.IO servers.
You just need to replace the default adapter by the Redis Adapter or another compatible adapter.
In certain cases, you may want to only broadcast to clients that are connected to the current server. You can achieve this with the local flag:
io.local.emit("hello", "world");
In order to target specific clients when broadcasting, please see the documentation about Rooms.
© 2014–2021 Automattic
Licensed under the MIT License.
https://socket.io/docs/v4/broadcasting-events