民意调查与长期民意调查 [英] polling vs long polling

查看:100
本文介绍了民意调查与长期民意调查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进入了这些显示投票的示例 vs javascript中的长轮询,但我不明白它们之间的区别。特别是关于长轮询示例,它如何保持连接打开?

I got onto these examples showing 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?

这是传统轮询方案的样子:

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

这是长轮询示例:

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

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

谢谢!

推荐答案

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

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.

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

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.

如果您需要更高性能(并且更优雅)的全双工客户端/服务器通信方式,请考虑使用WebSocket协议,太棒了!

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!

这篇关于民意调查与长期民意调查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆