PHP与ajax的长轮询

来源:互联网 发布:江苏凤凰数据有限公司 编辑:程序博客网 时间:2024/06/06 00:57

关于PHP与Jquery的ajax长轮询的简单的写法

html代码

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>长轮询</title></head><script src="../test/jquery-3.2.1.js" ></script><body>  <button type="" id="but" >测试</button>   <div id="bu"></div></body><script>    $(function(){    $("#but").bind('click',{but:$("#but")},function(e){        $.ajax({            type:"post",            url:"data.php",            data:{"time": Date.parse(new Date())/1000},               timeout: 5000,//5秒超时,可自定义设置 ,            dataType:"html",            success:function(result, textStatus){                                $("#bu").append("[state: " + textStatus + ", data: { " + result + "} ]<br/>");                if (textStatus == "success") { // 请求成功                      e.data.but.click();                 } ;            },            error:function(XHR, textStatus, errorThrown){                $("#bu").append("[state: " + textStatus + ", error: " + errorThrown + " ]<br/>");                  if (textStatus == "timeout") { // 请求超时                      e.data.but.click(); // 递归调用                  } else { // 其他错误,如网络错误等                      e.data.but.click();                  };             }        });    });});</script></html>

PHP代码

<?phpif(empty($_POST['time'])) exit();date_default_timezone_set("PRC");set_time_limit(0);//设置请求时间为无限,长连接$time = $_POST['time'];while (true) {        sleep(3); // 业务处理    $i = rand(0,100); // 产生一个0-100之间的随机数      if ($i > 50) { // 当$i>50 视为有数据变化          $responseTime = time();         echo ('result:  ' . $i . '  response_time:  ' . $responseTime . '  request_time:  '. $time . '  use_time:  '.($responseTime - $time));          exit();      } else { // 没有数据变化        sleep(8);         exit();      }  }  

测试结果为:


原创粉丝点击