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}\n",10000);      //推送间隔
            sb.AppendFormat("event:{0}\n", "message"); //绑定onmessage
            sb.AppendFormat("id:{0}\n", DateTime.Now.Ticks.ToString());
            sb.AppendFormat("data:{0}\n", 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+"\n\n")
    };
    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

posted @ 2019-08-06 11:46  山治先生  阅读(...)  评论(... 编辑 收藏