Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Comet by Example

Its feature is so called "server push", which google wave seems also leverages.

Can someone explain this concept by code snippet how it actually works in web application?

like image 890
user198729 Avatar asked Nov 05 '22 17:11

user198729


1 Answers

Some pseudo-javascript:

<script>
//open connection to the server, updateFunc is called every time server sends stuff
//For example ticker price for Google (GOOG)
var connection = CometLibrary.subscribe("http://server", "GOOG", updateFunc);

//data is JSON-encoded
function upudateFunc(data) {
  var elem = $("#GOOG .last");
  if (elem.value < data.last)
    elem.css("color", "green");
  else (elem.value > data.last)
    elem.css("color", "red");
  elem.value = data.last;
}

</script>
<span id="GOOG">GOOG: <span class="last"></span></span>

So the above code establishes a persistent connection to the server and the callback function gets called every time there is an update on the server. The price changes color if goes up or down and remains the color it was before if there is no change.

Alternative to that would be to have an interval timer making AJAX request every so many seconds which has the overhead of establishing and tearing down a connection.

like image 60
Igor Zevaka Avatar answered Dec 01 '22 17:12

Igor Zevaka