How to Keep Track of Clients with Websockets
With the introduction of HTML5, Websockets developers can leverage a lightweight, yet powerful, two-way communication model between client and server. Communication initiated from the server is a new addition in this model. The server is no longer simply responding to HTTP requests. Taking into consideration the client only needs to communicate with a single server address, the server now needs to keep track of open socket connections in a way that allows it to initiate communication with the proper client(s).
One way of accomplishing this is to label each open socket connection with a unique data point commonly shared between server and client.
See the example below with the ‘ws’ Node.js websocket library:
The ‘Clients’ object above stores all open socket connection objects with their respective usernames as a key/value pair.
The server relies on an initial message from the client with a username. Upon the connection & first message, the ‘clients’ instance stores the client object as a value of the username key:
Multiple clients can be stored and grouped for simple or complex applications and can be easily retrieved for initiating messages to client(s) in an intuitive way: