Suppose there is a webpage with dynamically generated content -- say a div containing the current number of connected browsers. When the count changes on the server I want all connected browsers to reload the count so that everyone sees the increment/decrement.
What's the best way to accomplish this?
Keywords: ajax, broadcast, browser, div, jquery
it is possible to write a java applet which can work as a network server. Once the applet has successfully started, it can report its port and ip number back to the remote server.
Then your server can send messages to the client server any time it feels like. Your java applet can then hand the message off to javascript, or do whatever else.
This method requires java plugin support however, which is far from universal.
As of Dec 2014, there is a W3C proposed recommendation called Server Sent Events (SSE) that would allow you to do that over HTTP: http://www.w3.org/TR/eventsource
It seems that it is a standardization of a group of techniques known as Comet. (which Darrel linked to in his answer)
A full example from 2013 with Sinatra can be found at: http://html5hacks.com/blog/2013/04/21/push-notifications-to-the-browser-with-server-sent-events/
There is also a 2010 HTML5 Rocks article: http://www.html5rocks.com/en/tutorials/eventsource/basics/ , but the spec is likely t have changed a bit since.
Most current browsers support this API, with the notable exception of IE11: http://caniuse.com/#feat=eventsource
I think COMET might be what you're looking for. Web Sockets would be ideal but lack of browser adoption wouldn't make it practical right now.
HTTP protocol is stateless by design. The only one way to achieve this is to implement client-side polling via AJAX.
Here's how to do server-push using ajax long-polling. The browser makes an ajax request which initiates server-side self-polling. The ajax request remains open, waiting for a response until the file changes, and as soon as it gets a response, it makes a new long-polling request.
Here's what it looks like with jQuery and php, implementing the example of live-updating a div in the html showing the number of clients currently connected:
index.html:
longpolling.js:
LongPolling.php:
NOTE: This does not track disconnects, so it's more like live-tracking the total number of pageviews. See Running server-side function as browser closes for info on keeping track of browser disconnects, ie, server-side action on client disconnect.
Pushlets?