[Java]基于长连接的服务器推技术

一般情况下,采用长连接,能持续的在客户端显示信息
比如

  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. %>  

这个代码会在客户端连续的显示时间。请注意,浏览器的正在下载是一直在运行中的。这个会让客户感到疑惑,难道还有东西在运行吗?

下面的这个方法,可以解决这个问题
我们先看服务器端代码。
使用了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. %>  

关键在客户端代码

  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>  

请注意其中的
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. %>  

看关键的客户端

  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>  

几个相关的文献

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏