【问题标题】:Which of the following javascripts long polling code should I use?我应该使用以下哪个 javascripts 长轮询代码?
【发布时间】:2014-09-05 07:56:35
【问题描述】:

我想使用长轮询。 我在谷歌上搜索并找到了许多有用的资源,而且由于很多,我开始混淆哪个更好。 以下是来自两个地方的三个代码 sn-ps。

https://gist.github.com/jasdeepkhalsa/4353139

// Long Polling (Recommened Technique - Creates An Open Connection To Server ∴ Fast)
(function poll(){
$.ajax({ 
    url: "server", 
    success: function(data)
             {
            //Update your dashboard gauge
             salesGauge.setValue(data.value);
             }, 
    dataType: "json",
    complete: poll,
    timeout: 30000 
   });
})();

// The setTimeout Technique (Not Recommended - No Queues But New AJAX Request Each Time ∴ Slow)
(function poll(){
setTimeout(function(){
$.ajax({ 
      url: "server", 
      success: function(data)
               {
               //Update your dashboard gauge
               salesGauge.setValue(data.value);
               //Setup the next poll recursively
                 poll();
               },
     dataType: "json"});
     }, 30000);
})();

https://github.com/panique/php-long-polling/blob/master/client/client.js

function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp};
$.ajax(
{
    type: 'GET',
    url: 'http://127.0.0.1/php-long-polling/server/server.php',
    data: queryString,
    success: function(data){
    // put result data into "obj"
    var obj = jQuery.parseJSON(data);
    // put the data_from_file into #response
    $('#response').html(obj.data_from_file);
    // call the function again, this time with the timestamp we just got from server.php
    getContent(obj.timestamp);
}
}
);
}

我的问题是哪个代码是长轮询的最佳实践? 我应该使用哪一个?

提前致谢。

【问题讨论】:

    标签: javascript ajax long-polling


    【解决方案1】:

    我认为第一种方法更好:

    1. 如果服务器配置为超时超过 30000 的长轮询,那么对于第一个,您将通过超时中断请求并发送新请求,将不会调用 success() 函数

      (虽然 complete() 将是,但错误也可以像这样在 error() 中处理

      error: function(x, t, m) {
          if(t==="timeout") {
              alert("got timeout");
          } else {
              alert(t);
          }
      }
      

      )。 而在第二个中,新请求将在 30000 之后发送,因此您将在客户端出现不可预测的行为(两个请求可以收到相同的答案,因此数据可能会重复)。

    2. 如果服务器配置为少于 30000 的长轮询,则在第二种方法中,客户端上的数据将不会及时更新。

    3. 如果服务器配置为 30000 的长轮询,那么应该没有任何区别。

    总而言之:第一种进近情况是可控的,而第二种进近情况并非总是如此。

    【讨论】:

    • 感谢您的意见和解释
    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 2011-09-30
    • 2013-03-05
    • 2012-03-25
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多