基于长连接的服务器推技术,使用htmlfile隐藏IE浏览器正在打开网页状态的代码

基于长连接的服务器推技术,使用htmlfile隐藏IE浏览器正在打开网页状态的代码

转自:http://www.java2000.net/p1787
一般情况下,采用长连接,能持续的在客户端显示信息
比如
  1. <%@ page language="java" c pageEncoding="utf-8"%>  
  2. <%  
  3.   out.flush();  
  4.   int number = 0;  
  5.   while (true) {  
  6.     out.println(new java.util.Date()+"  
  7. ");  
  8.     out.flush();  
  9.     Thread.sleep(100);  
  10.     System.out.print(".");  
  11.     if (number++ > 100) {  
  12.       break;  
  13.     }  
  14.   }  
  15. %>  
<%@ page language="java" c pageEncoding="utf-8"%>
<%
  out.flush();
  int number = 0;
  while (true) {
    out.println(new java.util.Date()+"
");
    out.flush();
    Thread.sleep(100);
    System.out.print(".");
    if (number++ > 100) {
      break;
    }
  }
%>
这个代码会在客户端连续的显示时间。请注意,浏览器的正在下载是一直在运行中的。这个会让客户感到疑惑,难道还有东西在运行吗?


下面的这个方法,可以解决这个问题

我们先看服务器端代码。
使用了prototype.js
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5. <title>Comet php backend</title>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  7. </head>  
  8. <body>  
  9. <script type="text/javascript">  
  10.   // KHTML browser don't share javascripts between iframes  
  11.   var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML");  
  12.   if (is_khtml)  
  13.   {  
  14.     var prototypejs = document.createElement('script');  
  15.     prototypejs.setAttribute('type','text/javascript');  
  16.     prototypejs.setAttribute('src','../js/prototype.js');  
  17.     var head = document.getElementsByTagName('head');  
  18.     head[0].appendChild(prototypejs);  
  19.   }  
  20.   // load the comet object  
  21.   var comet = window.parent.comet;  
  22. </script>  
  23. <%  
  24.   out.flush();  
  25.   int number = 0;  
  26.   while (true) {  
  27.     // 这里生成了调用js的代码  
  28.     out.println("<script type='text/javascript'>comet.printServerTime('" + new java.util.Date() + "');</script>");  
  29.     out.flush();  
  30.     Thread.sleep(100);  
  31.     // 控制台显示,程序正在运行,正式运行可去掉  
  32.     System.out.print(".");  
  33.     // 防止程序一直运行,给调试带来麻烦,正式运行可去掉  
  34.     if (number++ > 100) {  
  35.       break;  
  36.     }  
  37.   }  
  38. %>  
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet php backend</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
  // KHTML browser don't share javascripts between iframes
  var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML");
  if (is_khtml)
  {
    var prototypejs = document.createElement('script');
    prototypejs.setAttribute('type','text/javascript');
    prototypejs.setAttribute('src','../js/prototype.js');
    var head = document.getElementsByTagName('head');
    head[0].appendChild(prototypejs);
  }
  // load the comet object
  var comet = window.parent.comet;
</script>
<%
  out.flush();
  int number = 0;
  while (true) {
    // 这里生成了调用js的代码
    out.println("<script type='text/javascript'>comet.printServerTime('" + new java.util.Date() + "');</script>");
    out.flush();
    Thread.sleep(100);
    // 控制台显示,程序正在运行,正式运行可去掉
    System.out.print(".");
    // 防止程序一直运行,给调试带来麻烦,正式运行可去掉
    if (number++ > 100) {
      break;
    }
  }
%>
关键在客户端代码
  1.    
  2. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head>  
  6. <title>Comet demo</title>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  8. <script type="text/javascript" src="../js/prototype.js"></script>  
  9. </head>  
  10. <body>  
  11. <div id="content">The server time will be shown here</div>  
  12. <script type="text/javascript">  
  13. var url= 'testLinkData2.jsp';  
  14. var comet = {  
  15.   connection   : false,  
  16.   iframediv    : false,  
  17.     
  18.   initialize: function() {  
  19.     if (navigator.appVersion.indexOf("MSIE") != -1) {  
  20.       
  21.       // For IE browsers  
  22.       comet.connection = new ActiveXObject("htmlfile");  
  23.       comet.connection.open();  
  24.       comet.connection.write("<html>");  
  25.       comet.connection.write("<script>document.domain = '"+document.domain+"'");  
  26.       comet.connection.write("</html>");  
  27.       comet.connection.close();  
  28.       comet.iframediv = comet.connection.createElement("div");  
  29.       comet.connection.appendChild(comet.iframediv);  
  30.       comet.connection.parentWindow.comet = comet;  
  31.       comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='./"+url+"'></iframe>";  
  32.     } else if (navigator.appVersion.indexOf("KHTML") != -1) {  
  33.       // for KHTML browsers  
  34.       comet.connection = document.createElement('iframe');  
  35.       comet.connection.setAttribute('id',     'comet_iframe');  
  36.       comet.connection.setAttribute('src',    './'+url);  
  37.       with (comet.connection.style) {  
  38.         position   = "absolute";  
  39.         left       = top   = "-100px";  
  40.         height     = width = "1px";  
  41.         visibility = "hidden";  
  42.       }  
  43.       document.body.appendChild(comet.connection);  
  44.     } else {  
  45.       
  46.       // For other browser (Firefox...)  
  47.       comet.connection = document.createElement('iframe');  
  48.       comet.connection.setAttribute('id',     'comet_iframe');  
  49.       with (comet.connection.style) {  
  50.         left       = top   = "-100px";  
  51.         height     = width = "1px";  
  52.         visibility = "hidden";  
  53.         display    = 'none';  
  54.       }  
  55.       comet.iframediv = document.createElement('iframe');  
  56.       comet.iframediv.setAttribute('src''./'+url);  
  57.       comet.connection.appendChild(comet.iframediv);  
  58.       document.body.appendChild(comet.connection);  
  59.     }  
  60.   },  
  61.   // this function will be called from backend.php    
  62.   printServerTime: function (time) {  
  63.     $('content').innerHTML = time;  
  64.   },  
  65.   onUnload: function() {  
  66.     if (comet.connection) {  
  67.       comet.connection = false// release the iframe to prevent problems with IE when reloading the page  
  68.     }  
  69.   }  
  70. }  
  71. Event.observe(window, "load",   comet.initialize);  
  72. Event.observe(window, "unload", comet.onUnload);  
  73. </script>  
  74. </body>  
  75. </html>  
 
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../js/prototype.js"></script>
</head>
<body>
<div id="content">The server time will be shown here</div>
<script type="text/javascript">
var url= 'testLinkData2.jsp';
var comet = {
  connection   : false,
  iframediv    : false,
  
  initialize: function() {
    if (navigator.appVersion.indexOf("MSIE") != -1) {
    
      // For IE browsers
      comet.connection = new ActiveXObject("htmlfile");
      comet.connection.open();
      comet.connection.write("<html>");
      comet.connection.write("<script>document.domain = '"+document.domain+"'");
      comet.connection.write("</html>");
      comet.connection.close();
      comet.iframediv = comet.connection.createElement("div");
      comet.connection.appendChild(comet.iframediv);
      comet.connection.parentWindow.comet = comet;
      comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='./"+url+"'></iframe>";
    } else if (navigator.appVersion.indexOf("KHTML") != -1) {
      // for KHTML browsers
      comet.connection = document.createElement('iframe');
      comet.connection.setAttribute('id',     'comet_iframe');
      comet.connection.setAttribute('src',    './'+url);
      with (comet.connection.style) {
        position   = "absolute";
        left       = top   = "-100px";
        height     = width = "1px";
        visibility = "hidden";
      }
      document.body.appendChild(comet.connection);
    } else {
    
      // For other browser (Firefox...)
      comet.connection = document.createElement('iframe');
      comet.connection.setAttribute('id',     'comet_iframe');
      with (comet.connection.style) {
        left       = top   = "-100px";
        height     = width = "1px";
        visibility = "hidden";
        display    = 'none';
      }
      comet.iframediv = document.createElement('iframe');
      comet.iframediv.setAttribute('src', './'+url);
      comet.connection.appendChild(comet.iframediv);
      document.body.appendChild(comet.connection);
    }
  },
  // this function will be called from backend.php  
  printServerTime: function (time) {
    $('content').innerHTML = time;
  },
  onUnload: function() {
    if (comet.connection) {
      comet.connection = false; // release the iframe to prevent problems with IE when reloading the page
    }
  }
}
Event.observe(window, "load",   comet.initialize);
Event.observe(window, "unload", comet.onUnload);
</script>
</body>
</html>
请注意其中的
comet.connection = new ActiveXObject("htmlfile");
部分,就是这段代码生成了一个可以在IE浏览器下面,不再显示正在下载状态。据说这个是google的聪明人发现并应用于google的gtalk和gmail


最后,我们来看使用Ajax的查询方式,
服务器端在没有数据的情况下会阻塞,直到有数据。
服务器端
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  2. <%  
  3.   out.flush();  
  4.   int number = 0;  
  5.   while (true) {  
  6.     // 这里可以插入检测的代码,我后面直接休眠100毫秒代替了  
  7.     out.println("{'timestamp':'"+System.currentTimeMillis()+"','msg':'"new java.util.Date() + "'}");  
  8.     out.flush();  
  9.       
  10.     Thread.sleep(100);  
  11.     System.out.print(".");  
  12.     if (number++ > 1) {  
  13.       break;  
  14.     }  
  15.     break;  
  16.   }  
  17. %>  
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
  out.flush();
  int number = 0;
  while (true) {
    // 这里可以插入检测的代码,我后面直接休眠100毫秒代替了
    out.println("{'timestamp':'"+System.currentTimeMillis()+"','msg':'"+ new java.util.Date() + "'}");
    out.flush();
    
    Thread.sleep(100);
    System.out.print(".");
    if (number++ > 1) {
      break;
    }
    break;
  }
%>
看关键的客户端
  1.    
  2. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head>  
  6. <title>Comet demo</title>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  8. <script type="text/javascript" src="../js/prototype.js"></script>  
  9. </head>  
  10. <body>  
  11. <div id="content">内容</div>  
  12. <script type="text/javascript">  
  13. var Comet = Class.create();  
  14. Comet.prototype = {  
  15.   timestamp: 0,  
  16.   url: './testLinkData3.jsp',  
  17.   noerror: true,  
  18.   initialize: function() { },  
  19.   connect: function()  
  20.   {  
  21.     this.ajax = new Ajax.Request(this.url, {  
  22.       method: 'get',  
  23.       parameters: { 'timestamp' : this.timestamp },  
  24.       onSuccess: function(transport) {  
  25.         // handle the server response  
  26.         var response = transport.responseText.evalJSON();  
  27.         this.comet.timestamp = response['timestamp'];  
  28.         this.comet.handleResponse(response);  
  29.         this.comet.noerror = true;  
  30.       },  
  31.       onComplete: function(transport) {  
  32.         // send a new ajax request when this request is finished  
  33.         if (!this.comet.noerror)  
  34.           // if a connection problem occurs, try to reconnect each 5 seconds  
  35.           setTimeout(function(){ comet.connect() }, 5000);   
  36.         else  
  37.           this.comet.connect();  
  38.         this.comet.noerror = false;  
  39.       }  
  40.     });  
  41.     this.ajax.comet = this;  
  42.   },  
  43.   disconnect: function()  
  44.   {  
  45.   },  
  46.   handleResponse: function(response)  
  47.   {  
  48.     $('content').innerHTML += '<div>' + response['msg'] + '</div>';  
  49.   },  
  50.   doRequest: function(request)  
  51.   {  
  52.     new Ajax.Request(this.url, {  
  53.       method: 'get',  
  54.       parameters: { 'msg' : request }  
  55.     });  
  56.   }  
  57. }  
  58. var comet = new Comet();  
  59. comet.connect();  
  60. </script>  
  61. </body>  
  62. </html>  
 
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../js/prototype.js"></script>
</head>
<body>
<div id="content">内容</div>
<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {
  timestamp: 0,
  url: './testLinkData3.jsp',
  noerror: true,
  initialize: function() { },
  connect: function()
  {
    this.ajax = new Ajax.Request(this.url, {
      method: 'get',
      parameters: { 'timestamp' : this.timestamp },
      onSuccess: function(transport) {
        // handle the server response
        var response = transport.responseText.evalJSON();
        this.comet.timestamp = response['timestamp'];
        this.comet.handleResponse(response);
        this.comet.noerror = true;
      },
      onComplete: function(transport) {
        // send a new ajax request when this request is finished
        if (!this.comet.noerror)
          // if a connection problem occurs, try to reconnect each 5 seconds
          setTimeout(function(){ comet.connect() }, 5000); 
        else
          this.comet.connect();
        this.comet.noerror = false;
      }
    });
    this.ajax.comet = this;
  },
  disconnect: function()
  {
  },
  handleResponse: function(response)
  {
    $('content').innerHTML += '<div>' + response['msg'] + '</div>';
  },
  doRequest: function(request)
  {
    new Ajax.Request(this.url, {
      method: 'get',
      parameters: { 'msg' : request }
    });
  }
}
var comet = new Comet();
comet.connect();
</script>
</body>
</html>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值