Introduction: At Muse, we ****were working with a brand that wanted to know how many people were visiting their site at a given time, and have that information displayed to visitors.
To do this, I built a Live Counter component that made use of Ruby on Rails’ Action Cable. My goal was to see the amount of connections to a site, and display that information on the front end.
First, the Backend:
I had to make use of Action Cable and build a channel that would handle all of the network functions I needed for my live counter.
I made use of Action Cable’s periodically method, to send respective count of visitors to each visitor (or “subscriber”) on a site.
periodically :send_count, every: 5.seconds
I’ll show the frontend implementation in just a little bit- but the way this worked was when a visitor would go to a certain site, they would “subscribe” to that site’s Live Counter channel. The count that eventually got sent in my send_count method was the amount of subscribers.
def send_count
livecount_table = lookup_livecount(@slug)
@count = get_clients_count(livecount_table)
ActionCable.server.broadcast "livecounter", {type: "count", count: @count}
end
My get_clients_count method accessed the clients parameter of the passed in channel (which in this case would be the livecount_table). Since the clients parameter was an array, I would return the length of it to get the count of clients - subscribers - to the channel.
def get_clients_count(livecount)
livecount.clients.length
end
The frontend used JavaScript’s WebSocket API to send the subscription request over to the backend. It looked like this:
const socket = new WebSocket(websocket_url);
socket.addEventListener("open", () => {
const subscribe_msg = {
command: "subscribe",
identifier: JSON.stringify({ channel: "LivecounterChannel" }),
};
socket.send(JSON.stringify(subscribe_msg));
});
The subscribe_msg would call the subscribe method on the backend, which would initiate the connection between the WebSocket client and server. Once a client requests to subscribe, the server sends back a confirm_subscription request establishing the connection.