Live site visitor count
The setup for this will need to be a little different from the previous example since, in the Socket.io in action section, the socket connection was isolated to a single page. However, our site footer is not on a single page but every page! An implementation of this that would work well is wrapping the site in some context. By doing this, we would be able to access the count in other parts of the application if we needed to. Let's try this approach together:
- Modify the socket server's connection configuration with the following code:
io.on("connection", (socket) => { io.emit("count", io.engine.clientsCount); socket.on("disconnect", function () { io.emit("count", io.engine.clientsCount); }); });
We've changed this configuration quite a bit, so let's break it down. When a new socket connects to the server, we use
io.emit
. This function sends a message to all the connected clients instead...