While working on MuttonChop, I was unhappy with the way that the Web UI updated based on the state of of the player. The reason for my displeasure, was the use of polling to determine the player state.
In pseudo-code, the polling is something like the following:
//get the player state
state = get_player_state
//parse the state and update the UI accordingly
update_web_ui ( state )
//sleep for 2 seconds
//check the state again
Every 2 seconds, the Web UI checks the player state and then updates the UI.
Obviously I could shorten the polling time, but this leads to two issues that I'd rather not deal with.
- Constant polling creates far too much network traffic for my tastes.
- The steady amount of pulled data forces the client to work to much. If the client is running on a mobile device, this will cause unnecessary battery usage.
The solution, at least for me while coding MuttonChop, was to use a push technology known as Server Sent Events, which are part of the HTML5 specification.
In a nutshell, Server Sent Events work as follows:
- a client makes a connection to a server
- when the server has new data for the client, the server sends the data over the connection for the client to process
When not processing events, the client can be idle and save battery life (hopefully).
A Real World Scenario
While listening to music, when the track changes, the client interface should show the new track title and artist.
With polling, it may take 2 seconds for the UI to display the change.
With Server Sent Events, the update is almost in realtime.
The usage of Server Sent Events can make a sluggish polling based UI much more responsive to user interaction, and when dealing with Web apps, this speed up in responsiveness is very noticeable.
Since the connection for using Server Sent Events uses HTTP and the data is transferred as text, it should be fairly easy to write programs to process the events using any language that has an HTTP library.
To see what the events look like for MuttonChop (if you are interested in such things), open the command line and curl the "events" url of a playing muttonchop machine.
Taking this a step further, open a few connections to a MuttonChop server using a web browser or the curl method mentioned above, and change the volume on one client; the other clients should update the volume bar almost instantaneously. sweet sauce!
A great introduction to coding using Server Sent Events is available at http://www.html5rocks.com/en/tutorials/eventsource/basics/
Until later, happy hacking!