我正在尝试更多地了解长轮询以实时“操作”网站,看了一些视频,到目前为止我的想法是:
假设我有一个旧日期,它在sql上并且我在上面进行回显。只要长轮询知道旧日期将不同于根据setInterval函数的时间推移而出现的新日期,那么它就会知道......?
比如说我想展示博客中的所有文本都在mysql中,但我突然发布一篇新文章,那么在当前页面上的用户将会看到新文章的发表时间(难道不是吗?),那么长轮询代码怎么知道旧文章和新文章之间的区别呢?即使不给出冲突或在sql中刻录相同的日期。
我正在尝试更多地了解长轮询以实时“操作”网站,看了一些视频,到目前为止我的想法是:
假设我有一个旧日期,它在sql上并且我在上面进行回显。只要长轮询知道旧日期将不同于根据setInterval函数的时间推移而出现的新日期,那么它就会知道......?
比如说我想展示博客中的所有文本都在mysql中,但我突然发布一篇新文章,那么在当前页面上的用户将会看到新文章的发表时间(难道不是吗?),那么长轮询代码怎么知道旧文章和新文章之间的区别呢?即使不给出冲突或在sql中刻录相同的日期。
既然您最初的问题是这两种技术之间的区别,我将从这个方面开始:
AJAX轮询
使用AJAX轮询更新页面意味着您需要在定义的时间间隔内向服务器发送一个请求,它看起来像这样:
客户端发送一个请求到服务器,服务器立即响应。
一个简单的例子(使用jQuery)如下:
setInterval(function(){
$('#myCurrentMoney').load('getCurrentMoney.php');
}, 30000);
refresh = function() {
$('#myCurrentMoney').load('getCurrentMoney.php',function(){
refresh();
});
}
$(function(){
refresh();
});
getCurrentMoney.php
的输出加载到当前金额元素中,并在有回调时立即开始新的请求。<?
$time = time();
while ($newestPost <= $time) {
// note that this will not count as execution time on linux and you won't run into the 30 seconds timeout - if you wan't to be save you can use a for loop instead of the while
sleep(10000);
// getLatestPostTimestamp() should do a SELECT in your DB and get the timestamp of the latest post
$newestPost = getLatestPostTimestamp();
}
// output whatever you wan't to give back to the client
echo "There are new posts available";
这里我们不会有“无用”的请求。