layui中使用Server-Sent Events

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

前端代码:

         var evtSource;       
         layui.use('element', function () {
            var $ = layui.jquery;
            if (typeof (EventSource) !== "undefined") {
                evtSource  = new EventSource("event.webapi");
                evtSource.onmessage = function (e) {
                    console.log(e.data);
                }
                evtSource.onopen = function (e) {
                    console.log("event worked");
                }
                evtSource.onerror = function (e) {
                    console.log("event error");
                }
            } else {
                $("#result").html("抱歉,你的浏览器不支持 server-sent 事件...");
            }
            
        });
        //需要关闭时
        if(evtSource){evtSource.close()}

后端代码:

    public class EventProcess
    {
        public static void SendEvent(HttpListenerResponse response)
        {
            var output = response.OutputStream;
            response.Headers.Add("Cache-Control", "no-cache");
            response.Headers.Add("Connection", "keep-alive");
            response.ContentType = "text/event-stream;charset=UTF-8";
            //注意data:和\n\n是消息协议的一部分不能改动
            var data = Encoding.UTF8.GetBytes($"data: { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\n");
            output.Write(data, 0, data.Length);
            output.Flush();
            Thread.Sleep(500);
        }
    }

 

转载于:https://my.oschina.net/u/252343/blog/3029917

你可能感兴趣的:(python,前端,javascript)