5

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?

user198729
  • 55,886
  • 102
  • 239
  • 342

1 Answers1

2

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
  • 69,206
  • 26
  • 104
  • 125
  • How's `CometLibrary` implemented?I wander how do client side get response if the connection of request is not finished yet? – user198729 Jan 19 '10 at 11:25
  • 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 Jan 19 '10 at 12:17
  • As for how it;s implemented, trust me, you don't want to know. There is a lot of tricky hackery involved. – Igor Zevaka Jan 19 '10 at 12:19
  • 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 Jan 20 '10 at 03:02
  • precisely, as far as I am concerned, the comet client/server interaction is a protocol of its own. – Igor Zevaka Jan 20 '10 at 05:22