.net core HTML 5サポートサーバ送信イベント(Server-Sent Events)-一方向メッセージングデータプッシュ(C#例)

1746 ワード

使用するNetの直接アクセス下のサーバ-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}
", retry); sb.AppendFormat("event:{0}
", _event); sb.AppendFormat("id:{0}
", id); sb.AppendFormat("data:{0}

", data); return sb.ToString(); }

自分で直せば使える