从轮询到长时间轮询 [英] From polling to long polling

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

问题描述

所以我有一个脚本,该脚本使用基本轮询实时显示数据库中的记录总数

So I have a script that uses basic polling to show the total amount of records in the database in real time

所以没有什么复杂的,所以任何人都可以在长轮询结构中给我一个我的代码示例.之所以问这个问题,是因为google上的所有文章

so nothing complicated so can any one give me an example of my code in a long polling structure. The reason why I ask this question because all the articles on google

搜索为我提供了jQuery中的示例,但我似乎找不到适合我的情况的普通JavaScript示例.这是一个.gif屏幕截图 我的代码有效,所以你们知道我的意思了.

search gives me examples in jQuery I cant seem to find a plain JavaScript example that makes sense in my situation. This is a .gif screenshot of my code in action so you guys know what I mean in detail.

这是我需要转换或更改为长轮询的基本轮询示例代码.

This is my basic polling example code that I need to convert or change into long polling.

index.php

<style>
    #label{
    margin: 0;
    color: red;
    font-weight: bold;
    }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded',function(){

    /**********************************************************************
    Check for a new record amount in the data base
    **********************************************************************/

    function checkForNewRecords(){

    var xhr= new XMLHttpRequest();

    xhr.onreadystatechange= function(){

        if(xhr.readyState == 4){
        document.querySelector('#output').innerHTML= xhr.responseText;

        }
      }

    xhr.open('POST','check-for-new-records.php');
    xhr.send();  

    }

    setInterval(function(){checkForNewRecords()},1000);

    });
    </script>

    <p id='label'>Total records in the database in real time in basic polling</p>

    <div id='output'></div>

check-for-new-records.php

<?php

    $db_servername= 'localhost';
    $db_username='jd';
    $db_password= '1234';
    $db_name= 'test';

    $db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);

    $db_query= "SELECT COUNT(id) AS id FROM example";

    $db_result= $db_connect->query($db_query);
    $db_row= $db_result->fetch_object();

    $total_records= $db_row->id;

    ?>

    <style>
    #total-records{
    margin-top: 0;
    }
    </style>

    <p id='total-records'><?php echo $total_records; ?></p>

那么你们将如何将其转换为长时间轮询,请不要建议其他方法或不提供无用的答案,我只对我要的内容感兴趣,而且我很确定其他人也对纯JavaScript版本也很感兴趣,我之所以说这是因为我

So how would you guys convert this into long polling and please don't suggest other methods or don't provide an answer that is not helpful i'm only interested in what i'm asking for and i'm pretty sure others are also interested in a plain JavaScript version as well and the reason why I say this is because I

很长一段时间以来一直在网上询问这个话题,似乎没有人对回答这个话题感兴趣,或者如果他们如此认为为什么很难回答这个问题,为什么他们为什么这么多,而不是基于纯JavaScript而不是基于JavaScript呢?每个人都喜欢使用库.我只是说,我对从基于纯JavaScript的本主题中获得的无用答案感到不满意,只是提起了头脑.

been asking about this topic online for a long time and nobody seems interested in answering this or perhaps they think its too hard to answer this if so why is there so many jQuery examples about this topic and not based on plain JavaScript and not everyone likes to use libraries. I'm just saying I been unsatisfied about the unhelpful answers I been getting from this topic that is based on plain JavaScript, just a heads up.

推荐答案

请勿使用setInterval,而应使用setTimeout.

You should never use setInterval use setTimeout instead.

如果使用setTimeout,则轮询和长轮询的基本区别仅在发生延迟的地方.对于轮询,服务器将立即响应(即使未发生任何更改),客户端将等待n秒发送下一个请求.对于长时间轮询,服务器将等待响应,直到有新数据可用(或发生超时),并且客户端将在收到响应后立即发送新请求.

If you use setTimeout then basic difference for polling and long polling is only where the delay happens. For polling the server will respond immediatly (even if no change happened) and the client will wait n seconds to send the next request. For long polling the server will wait with the respond until new data is available (or a timeout occurs) and the client will immediately send a new request when it gets a response.

使用XMLHttpRequestfetchjQuery实施它绝对没有区别,客户端的唯一区别是下一个请求的延迟.

There is absolutely no different in implementing it with XMLHttpRequest, fetch or jQuery, the only difference client side is the delay for the next request.

投票:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 1000); // polling has the delay on the client
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

长轮询:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 0);
      // long-polling has the delay on the server 
      // the client initiates a new request immediatly after receiving the response.
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

另一方面,在服务器端,您通常需要更改几项内容才能有效地进行长时间轮询.

On the server side, on the other hand, you usually have to change a couple of things to make long polling work efficiently.

以轮询为目标的优化之间的重要区别在于,如何告诉服务器何时发送更新信息,但这与您用来请求数据的方法完全无关.

The important differences between polling and long polling that target optimizations, in how to tell the server when to send update informations, but thats completely independent form the method you use to request the data.

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

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