3

I'm developing a web-application in which I have a constant stream of data that is being received every 5 seconds or so in a java servlet (being read from a file written by another application). I want to push this data onto an html page and get it read in javascript so I can graph it in the d3 library.

At the moment I'm using a javascript function that calls the 'doGet' function of the servlet every 5 seconds. I'm worried this is creating a lot of overhead, or that it could be performed more efficiently. I know it's also possible to run "response.setIntHeader("Refresh", 5);" from the servlet.

Are there any other better ways?

Thanks in advance for the help!

zdani
  • 31
  • 2

1 Answers1

0

Short polling is currently probably the most common approach to solving the problem you describe

If you can cope with a few seconds lag in notification, then short polling is really simple, here is a basic example:

On page load, call this in your JS:

setInterval(checkFor, 30000);

The above will call a function checkFor() every 30 seconds (obviously, you can change the 30 seconds to any length of time - just adjust the 30000 in the above line according to how regular you want users to be updated).

Then, in your checkForNotifications function, just make an ajax call to your server asking if there are any updates - if the server says yes, then just display the alert using JS, if not (which will be most of the time most likely) then do nothing:

   function checkFor(){
    $.ajax({
    url: "your/server/url", 
    type: "POST",
    success: function( notification ) {
        //Check if any notifications are returned - if so then display alert
    },
    error: function(data){
        //handle any error 
      }
   });
 }
Parth Akbari
  • 641
  • 7
  • 24