Wednesday 2 April 2014

Read an HTTP streaming using only JavaScript


In one of the project where I've worked on, we had the requirement of  showing some live data graphs, where the input data were coming through a Streaming http.

The customer wanted to see the data real time with max 1 second delay, and doing some calculations we've came out that using a server process for this would  have not match the customer expectations, then we decided to go for a Client side approach using JavaScript.

This is why I discovered this easy and nice solution which worked very well and which met all the customer requirements. Here is the result:


The graphs were getting updated in real time thanks to:

  • On ready state change event, which was getting the streaming update and enqueue the values:

http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

  • The Chart Library which has been used to show the Graph:

http://www.flotcharts.org/

Here is the snippet used to get the Streaming update:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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==3 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","http://<Some HOST and PORT>/<STREAMING URL>",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>


No comments:

Post a Comment