• Asp.Net MVC Webapi Eventsource 实现时效消息


    ApiController

    后端API

     public System.Net.Http.HttpResponseMessage GetUnknownNotices()
            {
                var user = FormsAuth.GetUserData();
                var ns = new pl_NoticesService();
                var nl = ns.GetNoticeList(user.UserID, false);
                return createHttpRequestMessage(Newtonsoft.Json.JsonConvert.SerializeObject(nl));
            }
    
    System.Net.Http.HttpResponseMessage createHttpRequestMessage(string data)
            {
                var sb = new System.Text.StringBuilder();
                sb.AppendFormat("retry:{0}
    ",10000);      //推送间隔
                sb.AppendFormat("event:{0}
    ", "message"); //绑定onmessage
                sb.AppendFormat("id:{0}
    ", DateTime.Now.Ticks.ToString());
                sb.AppendFormat("data:{0}
    ", data);
    
                var response = new System.Net.Http.HttpResponseMessage
                {
                    Content = new System.Net.Http.StringContent(sb.ToString(), System.Text.Encoding.GetEncoding("UTF-8"),"text/event-stream")
                };
                response.StatusCode = System.Net.HttpStatusCode.OK;
                return response;
            }

    前端JS

    if (typeof (EventSource) != "undefined") {
        var es = new EventSource("/api/xxxx/GetUnknownNotices");
        es.onmessage = function (event) {
            var data = JSON.parse(event.data);
            $('#msgCount').text(data.length+"
    
    ")
        };
        es.onopen = function (event) {
            console.log("open:" + es.sta);
        };
        es.onerror = function (event) {
            console.log("error:" + es.readyState);
        };
    } 
    else {
            console.log("该浏览器不支持");
    }

    参考:

    https://www.runoob.com/html/html5-serversentevents.html

  • 相关阅读:
    Handler
    闹钟
    自动朗读 TTS
    语音转换成文本
    文件的存与读
    SurfaceView的绘图机制
    Chronometer
    拖动球
    如何整理一个被测对象的特性
    部门间沟通管理心得(持续不定期更新)
  • 原文地址:https://www.cnblogs.com/EminemJK/p/11308020.html
Copyright © 2020-2023  润新知