Broadcasting events
Socket.IO makes it easy to send events to all the connected clients.
Please note that broadcasting is a server-only feature.
To all connected clients
io.on("connection", (socket) => { io.emit("hello", "world"); }); |
To all connected clients except the sender
// server-side io.on("connection", (socket) => { socket.broadcast.emit("hello", "world"); }); |
With multiple Socket.IO servers
Broadcasting also works with multiple Socket.IO servers.
You just need to replace the default Adapter by the Redis Adapter. More information about it here.
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.on("connection", (socket) => { 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