长轮询如何工作javascript? [英] how does long polling work javascript?

查看:148
本文介绍了长轮询如何工作javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我明白,在长轮询中,您可以长时间保持与服务器的连接打开,直到您从服务器获得响应,然后再次轮询并等待下一个响应。但是,我似乎不明白如何编码它。下面有这个代码使用长轮询,但我似乎没有得到它

Hi I understand that in long polling you keep the connection with the server open for long till you a get a response back from the server and then poll again and wait for the next response. However i dont seem to understand how to code it. There is this code below which uses long polling but I dont seem to get it

(function poll(){
$.ajax({ url: "server", success: function(data){
   //update page based on data

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

但是如何在这里保持连接打开。我知道一旦得到服务器的响应就会再次触发poll功能。但是如何保持连接打开?

But how is the connection kept open here. I understand that "poll" function is fired again once the response from the server is got.But how is the connection kept open?

Edit1: - 如果有人也可以解释这里实际超时的内容

- It would be great if someone can also explain what would timeout actually do here

推荐答案

客户端无法强制服务器保持连接打开。 服务器根本就没有关闭连接。服务器必须在某个时候说就是这样,这里没有更多的内容,再见。在长轮询中,服务器根本不会这样做,并让客户端等待更多数据,随着更新的进行,它会逐渐涓涓细流。这是长时间的轮询。

The client cannot force the server to keep the connection open. The server is simply not closing the connection. The server will have to say at some point "that's it, there's no more content here, bye". In long polling, the server simply never does so and keeps the client waiting for more data, which it trickles out little by little as updates come in. That's long polling.

在客户端,可以在请求尚未完成时偶尔检查已经收到的数据。这样,有时可以通过相同的开放连接从服务器发送数据。在您的情况下,这没有完成, success 回调只会在请求完成时触发。它基本上是一种廉价的长轮询形式,服务器使客户端等待事件,发送有关此事件的数据,然后关闭连接。客户端将其作为触发器,处理数据,然后重新连接到服务器以等待下一个事件。

On the client side it's possible to check occasionally for the data which has already been received, while the request has not finished. That way data can occasionally be sent from the server over the same open connection. In your case this is not being done, the success callback will only fire when the request has finished. It's basically a cheap form of long polling in which the server keeps the client waiting for an event, sends data about this event and then closes the connection. The client takes that as the trigger, processes the data, then reconnects to the server to wait for the next event.

这篇关于长轮询如何工作javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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