.net core HTML5支持服务器发送事件(Server-Sent Events)-单向消息传递数据推送(C#示例)

用.net 的直接访问下边的    不了解 Server-Sent Events 直接访问下边链接  

https://www.cnblogs.com/xiongzaiqiren/archive/2017/05/18/6874283.html

以下是  net core 实列

 


        /// 
        /// ...api/MyAPI/ServerSentEvents
        /// 
        /// 
        [HttpGet("{teststr}")]
        public void ServerSentEvents()
        {
            string data = "";
            Response.Headers["Content-Type"] = "text/event-stream";
            Response.Headers["Cache-Control"] = "no-cache";
            Response.Headers["Connection"] = "keep-alive";
            //Response.Expires = -1
            //Response.Write("data: " & now())
            //Response.Flush()
            //Response.HttpContext.Response.Headers
            //唤醒默认的message
            data = ServerSentEventData(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.Ticks.ToString());
          
            Response.HttpContext.Response.Body.Write(System.Text.Encoding.Default.GetBytes(data),0, data.Length);
            Response.HttpContext.Response.Body.Write(System.Text.Encoding.Default.GetBytes(""),0, "".Length);

        }

        public string ServerSentEventData(string data, string id, string _event = "message", long retry = 1000)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("retry:{0}\n", retry);
            sb.AppendFormat("event:{0}\n", _event);
            sb.AppendFormat("id:{0}\n", id);
            sb.AppendFormat("data:{0}\n\n", data);
            return sb.ToString();
        }

自己改改 就能用

 

 

你可能感兴趣的:(.net core HTML5支持服务器发送事件(Server-Sent Events)-单向消息传递数据推送(C#示例))