IHttpAsyncHandler实现广播功能

IHttpAsyncHandler实现广播功能原理:第一次页面加载,发送一个请求到服务器,服务器挂起这个请求,等到有数据之后在返回这个请求,就实现了服务器主动推送的功能,就不用像以前一样使用js轮询去查询了。代码如下:

CometAsyncHandler.cs类

public class CometAsyncHandler:IHttpAsyncHandler
{
    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, object extraData)
    {
        WebAsynResult asyncResult = new WebAsynResult(context,callback,extraData);
        String content = context.Request.Params["content"];
        HttpResult.Instance().AddMessage(content, asyncResult);
        return asyncResult;
    }
    public void EndProcessRequest(IAsyncResult asyncResult)
    {
       
    }
    public void ProcessRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }
    public bool IsReusable
    {
        get { return false; }
    }
}

WebAsynResult.cs类

public class WebAsynResult : IAsyncResult
{
    bool _IsCompleted = false;
    private HttpContext context;
    private AsyncCallback cb;
    private object extraData;
    public WebAsynResult(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

    //调用此方法,实现返回数据到客户端
    public void Send(object data)
    {
        context.Response.Write(this.Content);
        if (cb != null)
        {
            cb(this);
        }
        _IsCompleted = true; ;
    }
}

HttpResult.cs类

public class HttpResult
{
    //所有请求
    List<WebAsynResult> clients = new List<WebAsynResult>();

    //类的单例
    private static HttpResult _Instance = new HttpResult();
    private HttpResult()
    {
    }
    public static HttpResult Instance()
    {
        return _Instance;
    }


    public void AddMessage(string content, WebAsynResult asyncResult)
    {
        //内容为connect,就挂起这个请求
        if (content == "connect")
        {
            clients.Add(asyncResult);
        }
        else
        {
            asyncResult.Content = content;
            asyncResult.Send(null);

            //遍历client,内容输出到客户端
            foreach (WebAsynResult result in clients)
            {
                result.Content = content;
                result.Send(null);
            }

            //清空所有缓存
            clients.Clear();
        }
    }
}

js调用代码

    <script>
        function coment() {
            var cont = "connect";
            $.ajax({
                type: "POST",
                url: "comet.asyn",
                data: { content: cont },
                success: function (data) {
                    coment();
                },
                error: function () {
                    coment();
                }
            })
        }
        window.onload = coment;
    </script>

web.config配置代码:在configuration节点下加:

  <system.webServer>
    <handlers>
      <add name="comet" verb="GET,POST" path="comet.asyn" type="CometAsyncHandler"/>
    </handlers>
  </system.webServer>

调用AddMessage实现广播代码:

WebAsynResult asyncResult = new WebAsynResult(HttpContext.Current, null, null);
HttpResult.Instance().AddMessage("广播内容", asyncResult);

这样只要是已经连接进来的客户端,都会收到这个广播内容,今天到此为止。

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券