一、comet是一种高级的ajax技术,实现了服务器向页面实时推送数据的技术。

应用场景

一、体育比赛比分、股票报价。

实现方式

一、实现comet有两种方式:长轮询和http流。

长轮询

长轮询(Long polling)/ comet

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);

  1. 客户端实现http流的方法```javascript
  2. var xhr = new XMLHttpRequest();
  3. received = 0; //最新消息在响应消息的位置
  4. xhr.onreadystatechange = function(){
  5. if(xhr.readyState == 3){
  6. result = xhr.responseText.substring(received);
  7. console.log(result);
  8. received += result.length;
  9. }else if(xhr.readyState == 4){
  10. console.log("完成消息推送");
  11. }
  12. }
  13. xhr.open('get', 'test1.php');
  14. 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);
} ?>

``` 页面接受到数据效果如下:
image.png | | —- |