Say:
- I have a website that contains a single toggle switch with 2 states.
- There are currently 2 (or more) clients viewing the site.
and
- 1 client flicks the toggle switch.
How can I reflect that change across everyone currently visiting the site?
The simplest way I thought of was to save the current state of the switch server side, and have the clients constantly send AJAX requests asking for the state of the switch, which it updates.
The problem with this approach is, especially when there are many clients, the server will be constantly spammed by requests; even if no change has happened.
The other approach I thought of was to notify the server when 1 client makes a change, and somehow broadcast that change to all the currently connected clients.
Unfortunately though, HTTP being stateless, I would have to maintain a list of currently connected clients server side. I don't know how I would detect when a client is no longer viewing the page though, or how I could send a message to a client without them first sending a request.
What is the simplest way to achieve this that doesn't rely on clients constantly polling the server?
In case it's not obvious, this is a greatly simplified example. My real project is a game where there will be many "switches", each of which may contain many different possible states.