title: How do I manage groups/rooms with node WebSockets?
body: <p><em>TL;DR</em> below.</p>
  
  <p>I am currently developing a React/Redux SPA that is driven by real-time data. I've decided to use <code>ws</code>, instead of <code>socket.io</code> since <code>socket.io</code> feels a bit high level for what I'm doing, I'd rather manage sockets myself.</p>
  
  <p>In saying that, I'm struggling to find a way to manage the separation of updates/messages per view/route. Since I'm using client-side routing it's per express route won't really work...</p>
  
  <p>Messages between the server and client via WebSockets are JSON with actions like <code>GET_ITEMS</code> then a response of <code>GET_ITEMS_SUCCESS</code> with an array of 'items' and for errors: <code>..._ERROR</code> etc. This is all fine, since it's just 1 to 1 transaction. Though the problem arises when broadcasting (1 to all) to all relevant clients when the server receives an update.</p>
  
  <p>So, I assume it best practice to limit these broadcasts to the clients that are viewing/want the data. So when viewing, for example, the <code>Item</code> page, there is no point in broadcasting updates to the <code>User</code> data since that is only used on the <code>User</code> page.</p>
  
  <p>I haven't been able to find any common practices when dealing with this sort of situation, just a few small outdated/barely used wrappers for <code>ws</code> that just add a few basic functions to leave/join but don't offer much flexibility with implementation.</p>
  
  <p>What I think <em>MIGHT</em> work is to have an object/array for each 'group'/'room', which stores the clients that are currently listening to updates from a given section. So a user would send an action to <code>INIT_LISTEN</code> (&amp; ``) with a param of category, e.g. <code>ITEM</code> for updates and other actions related to items. </p>
  
  <p><hr/>
  <em>TL;DR</em></p>
  
  <p><strong>What my question really boils down to is: How do I store a reference to a single socket? (<code>ws</code> client object? <code>ws</code> client ID?)</strong> Then, can I store this in an object/array to iterate through like below.</p>
  
  <pre><code> const ClientRooms = {
        Items: {
             {
                  ...ws
             }
             /* ...rest of the client */
        }
   }
  </code></pre>
  
  <p>or</p>
  
  <pre><code> const ClientRooms = {
        Items: [ "xyz" ] /* Array of ws ids */
   }
  </code></pre>
  
  <p>I have a "ping--pong" heartbeat function to keep clients active and prevent silent connection failures/disconnections. I can't find if <code>ws.terminate()</code> still fires the ws <code>close</code> event so I can iterate 'group'/'room' the object/array to find and remove instances of that client.</p>