Table of Contents
PHP实现Ajax长轮询
Home php教程 php手册 PHP实现Ajax长轮询

PHP实现Ajax长轮询

Jun 13, 2016 am 09:06 AM

PHP实现Ajax长轮询

 

传统的AJAX轮询方式,客服端以用户定义的时间间隔去服务器上查询最新的数据。种这种拉取数据的方式需要很短的时间间隔才能保证数据的精确度,但太短的时间间隔客服端会对服务器在短时间内发送出多个请求。

反转AJAX,就是所谓的长轮询或者COMET。服务器与客服端需要保持一条长时间的请求,它使得服务器在有数据时可以返回消息给客户端。

 

 

这里使用AJAX请求data.php页面获得‘success’的值,请求的时间达到80秒。在这80秒中若没有从服务端返回‘success’则一直保持连接状态,直到有数据返回或‘success’的值为0才关闭连接。在关闭连接后在继续下一次的请求。

index.html

 

Copy after login



在这里是无限的循环,循环的结束条件就是获取到了返回结果返回Json数据。

并且接受$_POST['time']参数来限制循环的超时时间,避免资源的过度浪费。(浏览器关闭不会发消息给服务器,使用可能一直循环下去)

data.php

<!--?php
    if(empty($_POST[&#39;time&#39;]))exit();      
    set_time_limit(0);//无限请求超时时间      
    $i=0;      
    while (true){      
        //sleep(1);      
        usleep(500000);//0.5秒      
        $i++;      
              
        //若得到数据则马上返回数据给客服端,并结束本次请求      
        $rand=rand(1,999);      
        if($rand<=15){      
            $arr=array(&#39;success&#39;=-->"1",&#39;name&#39;=>&#39;xiaoyu&#39;,&#39;text&#39;=>$rand);      
            echo json_encode($arr);      
            exit();      
        }      
              
        //服务器($_POST[&#39;time&#39;]*0.5)秒后告诉客服端无数据      
        if($i==$_POST[&#39;time&#39;]){      
            $arr=array(&#39;success&#39;=>"0",&#39;name&#39;=>&#39;xiaoyu&#39;,&#39;text&#39;=>$rand);      
            echo json_encode($arr);      
            exit();      
        }      
    }   
?>
Copy after login


 


运行效果:在图中可以看到无数据的请求时间达到了40S,在40S的请求中若获得数据则请求关闭。关闭之后继续下一次请求!

 

 

 

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)