views:

266

answers:

1

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?

+2  A: 

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.

Igor Zevaka
How's `CometLibrary` implemented?I wander how do client side get response if the connection of request is not finished yet?
have a play with this: http://goldfishserver.com/ If you type a message in another browser, you could see the stuff being updated in firefox. You will also see that new stuff is coming in on the same connection. The fact that that connection resets every 5 seconds is for connection error detection i think.
Igor Zevaka
As for how it;s implemented, trust me, you don't want to know. There is a lot of tricky hackery involved.
Igor Zevaka
CometLibrary is implemented in a fashion to be consistent with the appropriate server component. See http://stackoverflow.com/questions/2015443/jquery-comet-long-polling-and-streaming-tutorials/2044628#2044628 for details.
jvenema
precisely, as far as I am concerned, the comet client/server interaction is a protocol of its own.
Igor Zevaka