javascript 轮询与长轮询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18099798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:44:13  来源:igfitidea点击:

polling vs long polling

javascriptlong-pollingpolling

提问by Renaud

I got onto these examplesshowing polling vs long-polling in javascript, however I do not understand how they differ from one another. Especially regarding the long polling example, how does it keep its connection open?

我看到了这些在 javascript 中显示轮询与长轮询的示例,但是我不明白它们之间有何不同。特别是关于长轮询示例,它如何保持连接打开?

This is what the traditional polling scenario looks like:

这是传统的轮询场景的样子:

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

and this is the long polling example:

这是长轮询示例:

(function poll(){
  $.ajax({ url: "server", success: function(data){
    //Update your dashboard gauge
    salesGauge.setValue(data.value);

  }, dataType: "json", complete: poll, timeout: 30000 });
})();

Thanks!

谢谢!

回答by Alex

The difference is this: long polling allows for some kind of event-driven notifying, so the server is able to actively send data to the client. Normal polling is a periodical checking for data to fetch, so to say. Wikipedia is quite detailed about that:

不同之处在于:长轮询允许某种事件驱动的通知,因此服务器能够主动向客户端发送数据。正常轮询是定期检查要获取的数据,可以这么说。维基百科对此非常详细:

With long polling, the client requests information from the server in a way similar to a normal polling; however, if the server does not have any information available for the client, then instead of sending an empty response, the server holds the request and waits for information to become available (or for a suitable timeout event), after which a complete response is finally sent to the client.

对于长轮询,客户端以类似于普通轮询的方式向服务器请求信息;但是,如果服务器没有任何可供客户端使用的信息,则服务器不会发送空响应,而是持有请求并等待信息可用(或合适的超时事件),然后是完整的响应最后发给客户。

Long polling reduces the amount of data that needs to be sent because the server only sends data when there really IS data, hence the client does not need to check at every interval x.

长轮询减少了需要发送的数据量,因为服务器只在真正有数据时才发送数据,因此客户端不需要在每个时间间隔 x 进行检查。

If you need a more performant (and imho more elegant) way of full duplex client/server communication, consider using the WebSocket protocol, it's great!

如果您需要一种更高效(更优雅)的全双工客户端/服务器通信方式,请考虑使用 WebSocket 协议,这很棒!