通过例子理解彗星

发布于 2024-08-18 12:37:51 字数 105 浏览 5 评论 0原文

它的功能是所谓的“服务器推送”,google wave 似乎也利用了这一功能。

有人可以通过代码片段解释这个概念在网络应用程序中的实际工作原理吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪 2024-08-25 12:37:51

一些伪 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>

所以上面的代码建立了到服务器的持久连接,并且每次服务器上有更新时都会调用回调函数。如果价格上涨或下跌,价格就会改变颜色;如果没有变化,价格将保持之前的颜色。

替代方法是使用一个间隔计时器每隔几秒发出一次 AJAX 请求,这会产生建立和断开连接的开销。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文