layui中使用Server-Sent Events

前端代碼:javascript

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()}

後端代碼:html

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);
        }
    }
相關文章
相關標籤/搜索