AJAX长轮询之DotNet实现

今天和一个同事聊到了关于Web(传统)实时通讯的问题,其中包括轮询、长轮询、长连接。最后同事说长轮询对与.net来说比较难以实现(不使用任何框架)。

首先看一下什么是“长轮询”!定义如下:

长轮询:客户端向服务器发送Ajax请求,服务器接到请求后hold住连接,直到有新消息才返回响应信息并关闭连接,客户端处理完响应信息后再向服务器发送新的请求。

优点:在无消息的情况下不会频繁的请求。

缺点:服务器hold连接会消耗资源。

以上 “长轮询” 定义是我在网上抄的哦!

那么是不是只要满足以上所诉的内容长轮询是不是就成立呢?那就尝试一下!

建立数据库:

 
 
  1. ifnotexists(select1fromsys.databaseswherename='beidoudemo')
  2. begin
  3. CreateDatabasebeidoudemo
  4. end
  5. go
  6. usebeidoudemo
  7. go
  8. ifexists(select1fromsysobjectswherename='AjaxPolling'andtype='u')
  9. begin
  10. droptableAjaxPolling
  11. end
  12. go
  13. CreatetableAjaxPolling
  14. (
  15. idintidentityPrimarykey,
  16. userNamevarchar(30)notnull,
  17. passwordKeyvarchar(50)notnull
  18. )

选用Jquery中的AJAX方法发送异步请求,前台省了很多事情了!

具体代码请看:

 
 
  1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="LongPolling.aspx.cs"Inherits="AjaxFinder.LongPolling"%>
  2. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <htmlxmlns="http://www.w3.org/1999/xhtml">
  4. <headrunat="server">
  5. <scriptsrc="Scripts/jquery-1.4.1.js"type="text/javascript"></script>
  6. <title></title>
  7. <scripttype="text/javascript">
  8. varuserID=0;
  9. functionSendXHR(){
  10. $.ajax({
  11. type:"post",//AJAX请求类型
  12. url:"LongPollingServer.ashx",//请求url
  13. cache:false,//无缓存
  14. timeout:1000*80,//AJAX请求超时时间为60秒
  15. data:{time:60,userID:userID},//参数time时间为最多等待(后台保持)时间(60秒无论是否有数据立即返回),单位为秒。userID判断诗句是否为新数据的标识
  16. success:function(data,textStatus){
  17. varobj=document.getElementById("NameDisplay");
  18. //判断返回成功还是失败如果后台保持连接的时间一到并且没有新数据就会返回fail开头失败的数据
  19. if(data!=null&&data!=""&&!(data.indexOf("fail")!=-1)){
  20. varstrarr=data.split(",");
  21. //alert(strarr[0]);
  22. userID=strarr[0];
  23. obj.innerHTML="亲!有新用户注册哦!用户名:"+strarr[1];
  24. }
  25. else{
  26. obj.innerHTML="亲!暂无新用户注册哦";
  27. }
  28. SendXHR();//请求后立即发起AJAX请求
  29. },
  30. error:function(XMLHttpRequest,textStatus,errorThrown){
  31. //NewErrordosomething
  32. if(textStatus=="timeout"){
  33. //超时间
  34. SendXHR();
  35. }
  36. }
  37. });
  38. }
  39. window.
  40. SendXHR();
  41. }
  42. </script>
  43. </head>
  44. <body>
  45. <formid="form1"runat="server">
  46. <div>
  47. </div>
  48. <divid="NameDisplay">
  49. </div>
  50. </form>
  51. </body>
  52. </html>

前台数据请求已经准备好了,接下来看一下后台代码实现。具体代码如下:

 
 
  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Text;
  6. usingSystem.Net;
  7. usingSystem.Threading;
  8. usingSystem.Data;
  9. namespaceAjaxFinder
  10. {
  11. ///<summary>
  12. ///AJAX长轮询后台处理页面
  13. ///主要用于保持连接
  14. ///有数据返回,无数据继续保持连接超时返回
  15. ///author:bluescreen
  16. ///Date:2013-03-14
  17. ///blog:http://www.cnblogs.com/bluescreen/
  18. ///请不要关注代码编写规范等一些问题。这仅仅是一个DEMO
  19. ///还存在诸多问题
  20. ///</summary>
  21. publicclassLongPollingServer:IHttpHandler
  22. {
  23. publicvoidProcessRequest(HttpContextcontext)
  24. {
  25. /*
  26. context.Response.ContentType="text/plain";
  27. context.Response.Write("HelloWorld");*/
  28. intSendTime=0;//最多等待时间
  29. intuserID=0;//上一次的用户ID
  30. if(context.Request.Form["time"]!=null&&context.Request.Form["time"].ToString()!="")
  31. {
  32. SendTime=int.Parse(context.Request.Form["time"].ToString());//接收传来的的后台要保持时间
  33. }
  34. if(context.Request.Form["userID"]!=null&&context.Request.Form["userID"].ToString()!="")
  35. {
  36. userID=int.Parse(context.Request.Form["userID"].ToString());
  37. }
  38. inti=0;//计算超时时间(秒)
  39. while(true)
  40. {
  41. Thread.Sleep(1000);//停留一千毫秒(1秒)
  42. i++;
  43. if(i<SendTime)
  44. {
  45. if(NameStr(userID)!="")
  46. {
  47. context.Response.Write(NameStr(userID));
  48. break;
  49. }
  50. }
  51. if(i==SendTime)
  52. {
  53. context.Response.Write("fail:无数据");
  54. break;
  55. }
  56. }
  57. }
  58. ///<summary>
  59. ///获得用户名
  60. ///</summary>
  61. ///<paramname="userID"></param>
  62. ///<returns></returns>
  63. privatestringNameStr(intuserID)
  64. {
  65. stringresult=string.Empty;
  66. stringSqlstr="selecttop1ID,UserNamefromAjaxPollingOrderbyIDdesc";
  67. DataSetds=newDataSet();
  68. ds=SQLHelper.Query(Sqlstr,null);
  69. if(ds!=null)
  70. {
  71. if(ds.Tables[0].Rows.Count>=1)
  72. {
  73. if(int.Parse(ds.Tables[0].Rows[0][0].ToString())!=userID||0==int.Parse(ds.Tables[0].Rows[0][0].ToString()))
  74. {
  75. result=ds.Tables[0].Rows[0][0].ToString()+","+ds.Tables[0].Rows[0][1].ToString();
  76. }
  77. }
  78. }
  79. returnresult;
  80. }
  81. publicboolIsReusable
  82. {
  83. get
  84. {
  85. returnfalse;
  86. }
  87. }
  88. }
  89. }

以上代码经过测试的确符合 “长轮询” 的说法,那是不是可以说是长轮询呢?各位大牛你们怎么看?

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...