我正在尝试了解更多关于实时“操纵”网站的长轮询,看了一些视频,到目前为止我在想:
假设我有一个旧日期,sql 和我对其进行了回显。只要long polling就会知道旧日期会不会不一样,会根据setInterval函数不定时的看...?
假设我想显示一个博客的发布,其中所有文本都在 mysql 中,但是 repende 我发布了一个新的发布,当时页面上有谁,你会看到发布时间(不告诉我吗?) ,那么一个长轮询代码如何知道新旧发布之间的区别呢?吃甚至不给 sql 上刻的相同日期冲突或重复。
最佳答案
由于您最初的问题是这两种技术之间的区别是什么,我将从以下开始:
AJAX 轮询
使用 AJAX 轮询更新页面意味着您在定义的时间间隔内向服务器发送请求,如下所示:
客户端向服务器发送请求,服务器立即响应。
一个简单的示例(使用 jQuery)如下所示:
setInterval(function(){
$('#myCurrentMoney').load('getCurrentMoney.php');
}, 30000);
这样做的问题是,这会导致很多无用的请求,因为每个请求不会总是有新的东西。
AJAX 长轮询
使用 AJAX 长轮询意味着,客户端向服务器发送请求,服务器在响应之前等待新数据可用。这看起来像这样:
客户端发出请求,服务器“无规律”响应。一旦服务器响应,客户端将向服务器发送新请求。
客户端看起来像这样:
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";
这里我们不会有“无用”的请求。
关于php - 普通ajax和长轮询的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30252471/