2014-09-05 50 views
2

我想使用長輪詢。 我谷歌,發現很多有用的資源,並且因爲很多,我越來越迷惑哪個更好。 以下是來自兩個地方的三個代碼片段。我應該使用以下哪種JavaScript長查詢碼?

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); 
} 
} 
); 
} 

我的問題是它的代碼是長輪詢最佳做法? 我應該使用哪一個?

在此先感謝。

回答

3

第一種方法是在我看來更好:

  1. 如果配置爲長輪詢超時超過30000服務器,然後用第一個你將不得不超時斷請求和新請求將被髮送,成功()函數就不叫

    (而完整的()會,也錯誤可能是錯誤的()這樣的

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

    處理)。 雖然第二個請求會在30000之後發送,所以您在客戶端會有不可預知的行爲(兩個請求可能會收到相同的答案,因此數據可能會被複制)。

  2. 如果服務器配置爲使用少於30000的長輪詢,那麼在第二種方法中客戶端數據不會及時更新。

  3. 如果服務器配置爲使用30000進行長輪詢,那麼它應該沒有任何區別。

總結:在第一種方法情況下是可控的,而在第二種情況下 - 並非總是如此。

+0

感謝您的意見與解釋 – pmverma 2014-09-05 09:21:28