一、comet是一种高级的ajax技术,实现了服务器向页面实时推送数据的技术。
应用场景
一、体育比赛比分、股票报价。
实现方式
长轮询
http流
一、http流在页面整个生命周期内只使用一个http连接,具体使用方法即向浏览器发送一个请求,而服务器保持tcp连接打开,然后不断向浏览器发送数据。
| 【示例】客户端实现长轮询的方法```javascript var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ result = xhr.responseText console.log(result); xhr.open(‘get’, ‘test2.php’); //在获得数据后重新向服务器发起请求 xhr.send(null); } } xhr.open(‘get’, ‘test2.php’); xhr.send(null);
客户端实现http流的方法```javascriptvar xhr = new XMLHttpRequest();received = 0; //最新消息在响应消息的位置xhr.onreadystatechange = function(){if(xhr.readyState == 3){result = xhr.responseText.substring(received);console.log(result);received += result.length;}else if(xhr.readyState == 4){console.log("完成消息推送");}}xhr.open('get', 'test1.php');xhr.send(null);
以下为服务器端实时推送的实现方法,以php为例```javascript
<?php
ini_set(‘max_execution_time’, 10);
error_reporting(0);
$i = 0;
while(true){ //不断推送消息
echo “Number is $i\n”;
ob_flush(); //将php缓存冲出
flush(); //从php缓存中输出到tcp缓存
$i++;
sleep(1);
}
?>
```
页面接受到数据效果如下:
|
| —- |
