You can use Web Sockets for doing this, but be aware that Web Sockets are a new technology and in case of browser support you might have some troubles.
Web sockets are some kind of event listeners. They are awaiting events from the server like socket.onopen
-event.
So you could do the following to get this done on the client side:
At first there is the function which handles the response data...
function handleResponseData(data) {
// data could be JSON string for example
alert(data);
}
Then you create the web socket version of handling data...
function doSocket() {
socket = new WebSocket("ws://echo.websocket.org/");
socket.onmessage = function(event) {
handleResponseData(event.data);
}
}
And then the alternative version...
function doAlternative() {
window.setInterval(function() {
var xmlhttp;
if(window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200 &&
// Also check if server responded with data:
xmlhttp.responseText)
{
handleResponseData(xmlhttp.responseText);
}
}
xmlhttp.open("GET","echo.websocket.org",true);
xmlhttp.send();
}, 2000);
}
The only thing left to do is to check if web sockets are supported and to run the appropriate function...
function initialize() {
if(typeof(WebSocket) == "function") {
doSocket();
}
else {
doAlternative();
}
}
window.addEventListener("load", initialize, false);
With this code on the client side, you are now able to handle periodical updates.
But it is important to notice that as long as you run both versions, you will need two mechanisms on the server side to handle this:
- A socket which periodically sends updates to the client and
- A servlet which handles the requests sent in the interval function.
Finally, you can get some more information about web sockets here.