asp.net web 通過IHttpAsyncHandler介面進行訊息推送

來源:互聯網
上載者:User

標籤:服務   query   post   函數   模式   www   als   thread   建立   

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 = 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="Scripts/jquery-1.10.2.min.js"></script>    <script type="text/javascript" src="Scripts/myJS.js"></script></head><body>      廣播內容:  <input type="text" id="content" /><br />      訊息記錄:        <div id="divResult"></div>        <input type="button" id="btnSend" value="廣播" /></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.configIIS傳統模式配置 <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介面進行訊息推送

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.