首页 > 代码库 > asp.net web 通过IHttpAsyncHandler接口进行消息推送

asp.net web 通过IHttpAsyncHandler接口进行消息推送

1.创建Comet_by_ASP.NET web项目
2.handler类和result类
namespace Handle
{
    /// <summary>
    /// Summary description for AsnyHandler
    /// </summary>
    public class AsnyHandler : IHttpAsyncHandler
    {
        public AsnyHandler()
        {
        }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            //myAsynResult为实现了IAsyncResult接口的类,当不调用cb的回调函数时,该请求不会返回到给客户端,会一直处于连接状态
            myAsynResult asyncResult = new myAsynResult(context, cb, extraData);
            String content = context.Request.Params["content"];

            //向Message类中添加该消息
            Messages.Instance().AddMessage(content, asyncResult);
            return asyncResult;
        }

        #region 不必理会

        public void EndProcessRequest(IAsyncResult result)
        {

        }

        public bool IsReusable
        {
            get { return false; ; }
        }

        public void ProcessRequest(HttpContext context)
        {
        }
        #endregion
    }
    public class myAsynResult : IAsyncResult
    {
        bool _IsCompleted = false;
        private HttpContext context;
        private AsyncCallback cb;
        private object extraData;
        public myAsynResult(HttpContext context, AsyncCallback cb, object extraData)
        {
            this.context = context;
            this.cb = cb;
            this.extraData =http://www.mamicode.com/ extraData;
        }
        private string _content;
        public string Content
        {
            get { return _content; }
            set { _content = value; }
        }

        #region IAsyncResult接口
        public object AsyncState
        {
            get { return null; }
        }

        public System.Threading.WaitHandle AsyncWaitHandle
        {
            get { return null; }
        }

        public bool CompletedSynchronously
        {
            get { return false; }
        }
        public bool IsCompleted
        {
            get { return _IsCompleted; }
        }
        #endregion

        //在Message类中的添加消息方法中,调用该方法,将消息输入到客户端,从而实现广播的功能
        public void Send(object data)
        {
            context.Response.Write(this.Content);
            if (cb != null)
            {
                cb(this);
            }
            _IsCompleted = true; ;
        }
    }
}
3.Messages类
using Handle;
using System;
using System.Collections.Generic;
using System.Web;
namespace Handle
{
    /// <summary>
    /// Summary description for Messages
    /// </summary>
    public class Messages
    {
        //记录所有请求的客户端
        List<myAsynResult> clients = new List<myAsynResult>();

        #region 实现该类的单例
        private static readonly Messages _Instance = new Messages();
        private Messages()
        {
        }
        public static Messages Instance()
        {
            return _Instance;
        }
        #endregion

        public void AddMessage(string content, myAsynResult asyncResult)
        {
            //当传入的内容为"-1"时,表示为建立连接请求,即为了维持一个从客户端到服务器的连接而建立的连接
            //此时将该连接保存到 List<myAsynResult> clients中,待再有消息发送过来时,该连接将会被遍历,并且会将该连接输出内容后,结束该连接
            if (content == "-1")
            {
                clients.Add(asyncResult);
            }
            else
            {
                //将当前请求的内容输出到客户端
                asyncResult.Content = content;
                asyncResult.Send(null);

                //否则将遍历所有已缓存的client,并将当前内容输出到客户端
                foreach (myAsynResult result in clients)
                {
                    result.Content = content;
                    result.Send(null);
                }

                //清空所有缓存
                clients.Clear();
            }
        }
    }
}
4.Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        *{ font-size:12px;}
        #divResult
        {
             border:1px solid #000;
             width:250px;
        }
    </style>
    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/myJS.js"></script>
</head>
<body>
      广播内容:  <input type="text" id="content" /><br />
      消息记录:
        <div id="divResult"></div>
        <input type="button" id="btnSend" value=http://www.mamicode.com/"广播" />
</body>
</html>
5.myjs类
/// <reference path="jquery-1.3.2.min.js" >
$(document).ready(function () {
    function send() {
        //向comet_broadcast.asyn发送请求,消息体为文本框content中的内容,请求接收类为AsnyHandler
        $.post("comet_broadcast.asyn", { content: $("#content").val() });
        
        //清空内容
        $("#content").val("");
    }

    function wait() {
        $.post("comet_broadcast.asyn", { content: "-1" },
         function (data, status) {
             var result = $("#divResult");
             result.html(result.html() + "<br/>" + data);
             
             //服务器返回消息,再次立连接
             wait();
         }, "html"
         );
    }

    //初始化连接
    wait();

    $("#btnSend").click(function () { send(); });
    $("#content").keypress(function (event) {
        if (event.keyCode == 13) {
            send();
        }
    });
});
6.web.config
IIS经典模式配置
 <system.webServer>      
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
     <handlers>
      <add name="comet_broadcast" path="comet_broadcast.asyn" type="Handle.AsnyHandler" verb="POST,GET"/>
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
兼容旧版iis
<system.web>
     <httpHandlers>
       <add name="comet_broadcast" path="comet_broadcast.asyn" type="Handle.AsnyHandler" verb="POST,GET"/>
      </httpHandlers>
</system.web>
7.最后恭祝你身体健康,万事如意。

 

asp.net web 通过IHttpAsyncHandler接口进行消息推送