myHotTake

Tag: online status monitoring

  • How to Track Online Users with WebSockets in JavaScript

    If you find this story helpful, feel free to like or share it!


    I’m the host of a radio station, and I want to keep track of all my listeners to know who’s tuned in and who’s not. Each listener has a special radio that can send signals back to me. This radio connection is like a WebSocket, a two-way communication line between my station and the listener.

    One day, as I start my broadcast, I imagine each listener turning on their radio and sending me a signal: “Hey, I’m online!” Each signal they send is a little ping, telling me they’re listening in. As the host, I jot down a list of everyone who’s tuned in, just like a server keeping track of connected users.

    As the show goes on, I occasionally send out little messages to my listeners, like song titles or trivia questions. Their radios are always ready to receive, just like a WebSocket connection always being open for data exchanges.

    Now, sometimes a listener decides to switch off their radio or maybe their battery runs out. When that happens, their radio sends me a final signal: “Goodbye, I’m going offline.” I scratch their name off my list. This is akin to a WebSocket connection closing when a user goes offline, and the server updating its records.

    But sometimes, I don’t hear a goodbye signal. Maybe their radio just went silent due to bad reception. To make sure I know who’s really there, every so often, I send out a heartbeat signal: “Are you still with me?” Those radios that can still hear me will reply, “Yes, I’m here!” If I don’t get a response, I know they’re no longer tuned in, and I update my list accordingly.

    In this way, my radio station, with its trusty radios, helps me keep track of who’s listening and who’s not, much like how presence tracking works with WebSockets to monitor online and offline users. Each connection is alive, constantly communicating, ensuring I always know who’s part of my audience.


    First, I set up my radio station (server) using Node.js with the ws library, which lets me handle WebSocket connections. Here’s a basic example:

    const WebSocket = require('ws');
    const wss = new WebSocket.Server({ port: 8080 });
    
    const listeners = new Set();
    
    wss.on('connection', (ws) => {
      // A new radio turns on
      listeners.add(ws);
      console.log('A new listener has tuned in.');
    
      // Handle messages from the listener
      ws.on('message', (message) => {
        console.log(`Received message: ${message}`);
      });
    
      // Handle the listener going offline
      ws.on('close', () => {
        listeners.delete(ws);
        console.log('A listener has tuned out.');
      });
    
      // Heartbeats to check if listeners are still online
      const heartbeat = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.send('Are you still there?');
        }
      }, 30000);
    
      ws.on('pong', () => {
        console.log('Listener is still online.');
      });
    
      ws.on('close', () => {
        clearInterval(heartbeat);
      });
    });

    In this code, each time a listener connects, I add them to my list of listeners. When they send a message, I log it, simulating the interaction of answering trivia or song titles.

    When a listener goes offline (closes the connection), I remove them from the list, just like crossing their name off my radio station’s roster.

    To ensure my listener list is accurate, I periodically send a heartbeat message asking, “Are you still there?” If a listener is still connected, they respond, and I know they’re still tuned in. This is akin to checking if their radio signal is still strong.

    On the client side, here’s a simple JavaScript example of how a listener might interact with the station:

    const ws = new WebSocket('ws://localhost:8080');
    
    ws.onopen = () => {
      console.log('Connected to the radio station.');
      ws.send('Hello from the listener!');
    };
    
    ws.onmessage = (event) => {
      console.log(`Station says: ${event.data}`);
      // Respond to heartbeats
      if (event.data === 'Are you still there?') {
        ws.send('Yes, I am here!');
      }
    };
    
    ws.onclose = () => {
      console.log('Disconnected from the radio station.');
    };

    This client code connects to my radio station, sends a greeting, and listens for messages. When a heartbeat is received, it responds to let me know they’re still tuned in.

    Key Takeaways:

    1. WebSockets enable real-time, two-way communication between the server and clients, much like a radio station and its listeners.
    2. JavaScript provides the tools to set up WebSocket servers and clients, allowing you to track online/offline status effectively.
    3. Heartbeats are a crucial technique to ensure the server’s presence list is accurate, checking if connections are still active.