Gaining further insights with rooms
There is one element to socket.io events that we have not talked about yet but could be of great benefit in our application – rooms. Rooms are channels that a socket can join
and leave
. The server can emit messages to a room to broadcast an event to a subset of the clients connected to the server.
To demonstrate the concept of rooms, we will be breaking down our visitor count into more granular stats. Not only will we display to the user the count of total users on the site, but we will also provide them with the details of how many people are on their current page of the site. Let's get started:
- Update your
server/app.js
file's socket code so that it includes a new event:// defined at top of file const pathToRoom = (path) => 'Page-${path}'; // defined in socket configuration socket.on("page-update", ({ currentPage, previousPage }) => { if (previousPage) { const previousRoom = pathToRoom...