Difference between a normal ajax and long polling

后端 未结 1 414
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 13:13

I\'m trying to understand more about long polling to \"manipulate\" a website in real time, saw some videos and I\'m thinking so far:

Say I have an old date that the

相关标签:
1条回答
  • 2020-12-14 13:31

    Since your initial question was what the difference between the two techniques is, I will start with this:

    AJAX polling

    Using AJAX polling to update a page will mean, that you send a request in a defined interval to the server, which would look like this:

    AJAX polling

    The client sends a request to the server and the server responses immediately.

    A simple example (using jQuery) would look like this:

    setInterval(function(){
        $('#myCurrentMoney').load('getCurrentMoney.php');
    }, 30000);
    

    The problem with this is, that this will cause a lot of useless requests since there won't be always new things on every request.

    AJAX long polling

    Using AJAX long polling will mean, that the client sends a request to the server and the server waits for new data to be available before he responds. This would look like this:

    AJAX long polling

    The client sends a request and the server responds "irregularly". As soon as the server responds, the client will send a new request to the server.

    The client side would look like this:

    refresh = function() {
        $('#myCurrentMoney').load('getCurrentMoney.php',function(){
            refresh();
        });
    }
    
    $(function(){
        refresh();
    });
    

    What this will do is just load the getCurrentMoney.php's output into the current money element and as soon as there is a callback, start a new request.

    On the server side you usually use a loop. To solve your question how the server will know, which are new publications: either you pass the timestamp of the newest to the client available publication to the server or you use the time of the "long polling start" as indiactor:

    <?
    $time = time();
    
    while ($newestPost <= $time) {
        // note that this will not count as execution time on linux and you won't run into the 30 seconds timeout - if you wan't to be save you can use a for loop instead of the while
        sleep(10000);
        // getLatestPostTimestamp() should do a SELECT in your DB and get the timestamp of the latest post
        $newestPost = getLatestPostTimestamp();
    }
    
    // output whatever you wan't to give back to the client
    echo "There are new posts available";
    

    Here we won't have "useless" requests.

    0 讨论(0)
提交回复
热议问题