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 actu开发者_JS百科ally works in web application?
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.
精彩评论