利用Jquery实现http长连接(LongPoll)

转载: http://blog.csdn.net/yuxuanji/archive/2009/04/13/4069732.aspx

 

C#代码 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryAjaxLongPoll.aspx.cs" Inherits="JqueryAjaxLongPoll" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>无标题页</title>  
  8.     <script type="text/javascript" src="script/jquery-1.2.6.js"></script>  
  9.     <script type="text/javascript">  
  10.         $(document).ready(function(){  
  11.             $("#Button1").bind("click",{btn:$("#Button1")},function(evdata){  
  12.                 $.ajax({  
  13.                     type:"POST",  
  14.                     url:"JqueryAjaxLongPoll.aspx",  
  15.                     dataType:"json",  
  16.                     timeout:10000,  
  17.                     data:{ajax:"1",time:"10000"},  
  18.                     success:function(data,textStatus){  
  19.                             //alert("ok!");  
  20.                             evdata.data.btn.click();  
  21.                     },  
  22.                     complete:function(XMLHttpRequest,textStatus){  
  23.                             if(XMLHttpRequest.readyState=="4"){  
  24.                                 alert(XMLHttpRequest.responseText);  
  25.                             }  
  26.                     },  
  27.                     error: function(XMLHttpRequest,textStatus,errorThrown){  
  28.                             //$("#ajaxMessage").text($(this).text()+" out!")  
  29.                             alert("error:"+textStatus);  
  30.                             if(textStatus=="timeout")  
  31.                                 evdata.data.btn.click();  
  32.                     }  
  33.                 });  
  34.             });  
  35.   
  36.             /*$("#ajaxMessage").ajaxStart(function(){ 
  37.                 $(this).text("准备建立请求.readyState0:"); 
  38.             }); 
  39.             $("#ajaxMessage").ajaxSend(function(evt, request, settings){ 
  40.                 $(this).text("开始请求,准备发送数据.readyState1:"+request.readyState); 
  41.             }); 
  42.             $("#ajaxMessage").ajaxComplete(function(event,request, settings){ 
  43.                 if(request.status==200) 
  44.                     $(this).text("请求完成.readyState4:"+request.readyState); 
  45.             }); 
  46.             $("#ajaxMessage").ajaxStop(function(){ 
  47.                 $(this).text("请求结束."); 
  48.             });*/  
  49.         });  
  50.     </script>  
  51. </head>  
  52. <body>  
  53.     <form id="form1" runat="server">  
  54.     <div>  
  55.         <input id="Button1" type="button" value="AjaxLongPoll" />  
  56.         <label id="ajaxMessage"></label>  
  57.     </div>  
  58.     </form>  
  59. </body>  
  60. </html>  
  61.   
  62. using System;  
  63. using System.Data;  
  64. using System.Configuration;  
  65. using System.Collections;  
  66. using System.Web;  
  67. using System.Web.Security;  
  68. using System.Web.UI;  
  69. using System.Web.UI.WebControls;  
  70. using System.Web.UI.WebControls.WebParts;  
  71. using System.Web.UI.HtmlControls;  
  72. using System.Threading;  
  73.   
  74. public partial class JqueryAjaxLongPoll : System.Web.UI.Page  
  75. {  
  76.     protected void Page_Load(object sender, EventArgs e)  
  77.     {  
  78.         if (Request.Form["ajax"] == "1")  
  79.         {  
  80.             //Response.End();  
  81.             int time = Convert.ToInt32(Request.Form["time"]);  
  82.             DateTime date1 = DateTime.Now.AddMilliseconds((double)time);  
  83.             bool ready = false;  
  84.             while (Response.IsClientConnected)  
  85.             {  
  86.                 Thread.Sleep(3000);  
  87.                 if (DateTime.Compare(date1, DateTime.Now) < 0)  
  88.                 {  
  89.                     Response.End();  
  90.                     break;  
  91.                 }  
  92.                 //ready = true;  
  93.                 if (ready)  
  94.                 {  
  95.                     Response.Write("SetValue('" + DateTime.Now.ToString() + "')");  
  96.                     //Response.Flush();  
  97.                     Response.End();  
  98.                     break;  
  99.                 }  
  100.                 else  
  101.                 {  
  102.   
  103.                 }  
  104.             }  
  105.         }  
  106.         else  
  107.         {  
  108.             if (!Page.IsPostBack)  
  109.             {  
  110.   
  111.             }  
  112.         }  
  113.     }  
  114. }  
C#代码 
  1.    

 

写道
思路: 

利用jquery,很方便的就能实现ajax,上面设置了ajax的timeout时间,由于设置了timeout将会造成不能保持长连接,到了时间ajax自动会报“超时”的错误,也就是会调用error方法,此时textStatus=="timeout",timeout后重新进行ajax请求。服务器接受ajax请求的时候,会接收一个超时时间的值,超时的情况下服务器端的处理也立即停止。当客户端成功获取返回结果时,也会立即进行新的ajax请求,如此循环。 

为什么要设置客户端的ajax超时值呢?因为服务器为了保持请求(阻塞请求),必须有一个无限循环,循环的结束条件就是获取到了返回结果,如果客户端关闭了(客户端浏览器的关闭不会发消息给服务器),服务器无法知道客户端已经关了,这个请求没必要处理下去了。最终会造成资源过度浪费,只要用一个折中的办法,限制超时时间。 

可以不必设置客户端ajax的超时时间,但进行请求的时候传递一个超时值给服务器,服务器在处理的时候,如果超时时间到了的话,还没有客户端需要的结果,这时传递一个超时信息给客户端,客户端接收到了此信息,根据情况重新进行ajax请求。XMLHttpRequest没有超时的参数,Jquery用window.setTimeout自己封装的(到了定时时间运行超时处理方法,和XMLHttpRequest结束方法)。可以根据这个思路来改变一下,IBM上介绍的LONG POLL好像也是这样的。

 

C#代码 
  1. $(document).ready(function(){  
  2.             $("#Button1").bind("click",{btn:$("#Button1")},function(evdata){  
  3.                 $.ajax({  
  4.                     type:"POST",  
  5.                     url:"JqueryAjaxLongPoll.aspx",  
  6.                     dataType:"json",  
  7.                     data:{ajax:"1",time:"6000000"},  
  8.                     success:function(data,textStatus){  
  9.                             //成功  
  10.                             if(data.success=="1"){  
  11.                                 //客户端处理  
  12.                                 //...  
  13.                                 ///重新请求  
  14.                                 evdata.data.btn.click();  
  15.                             }  
  16.                             //超时  
  17.                             if(data.success=="0"){  
  18.                                 evdata.data.btn.click();  
  19.                             }  
  20.                     },  
  21.                     complete:function(XMLHttpRequest,textStatus){  
  22.                             if(XMLHttpRequest.readyState=="4"){  
  23.                                 alert(XMLHttpRequest.responseText);  
  24.                             }  
  25.                     },  
  26.                     error: function(XMLHttpRequest,textStatus,errorThrown){  
  27.                             //$("#ajaxMessage").text($(this).text()+" out!")  
  28. //                            alert("error:"+textStatus);  
  29. //                            if(textStatus=="timeout")  
  30.                                 evdata.data.btn.click();  
  31.                     }  
  32.                 });  
  33.             });  
  34.   
  35. 后台代码变更后:  
  36. if (Request.Form["ajax"] == "1")  
  37.         {  
  38.             int time = Convert.ToInt32(Request.Form["time"]);  
  39.             DateTime date1 = DateTime.Now.AddMilliseconds((double)time);  
  40.             bool ready = false;  
  41.             while (Response.IsClientConnected)  
  42.             {  
  43.                 Thread.Sleep(3000);  
  44.                 if (DateTime.Compare(date1, DateTime.Now) < 0)  
  45.                 {  
  46.                     Response.Write("{success:'0'}");  
  47.                     Response.End();  
  48.                     break;  
  49.                 }  
  50.                 //此处进行请求处理,有结果了置ready = true  
  51.                 //ready = true;  
  52.                 if (ready)  
  53.                 {  
  54.                     Response.Write("{success:'1'}");  
  55.                     Response.End();  
  56.                     break;  
  57.                 }  
  58.             }  
  59.         }  
  60.         else  
  61.         {  
  62.             if (!Page.IsPostBack)  
  63.             {  
  64.   
  65.             }  
  66.         }  
  67.   
  68. 上面的方法应该就可以满足要求了,具体的超时时间可以根据情况来设置。这也是我根据IBM上介绍的“server push”思路,来实现了其中的一种,也不知道有没有问题,还请大家多多赐教。  
posted on 2010-02-05 15:15  上午的绝缘杯  阅读(23955)  评论(2编辑  收藏  举报