星空网 > 软件开发 > 网页设计

[ASP.NET MVC] Real

最近有时间,打算看看SignalR,顺便了解一下Server Sent Events。

 

Controller

输出的数据格式为:data:[数据]\n\n。输出的数据尝试8000多字符也没问题,具体的上限就没试了。但是如果数据里也包含\n\n的话,数据就会被截断。

 1 public class HomeController : Controller 2 { 3   // GET: Home 4   public ActionResult Index() 5   { 6     return View(); 7   } 8  9   //Server-Sent Event10   public void Sse()11   {12     Random random = new Random();13 14     //设置HTTP MIME 类型,不缓存页面15     Response.ContentType = "text/event-stream";16     Response.CacheControl = "no-cache";17       18     while (Response.IsClientConnected)19     {20       try21       {22         string data = SseData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " from http://www.cnblogs.com/ainijiutian/");23         Response.Write(data);24         Response.Flush();25 26         System.Threading.Thread.Sleep(random.Next(500, 5000));27       }28       catch (Exception ex)29       {30         System.Diagnostics.Debug.WriteLine(ex.Message);31       }32     };33       34     Response.End();35     Response.Close();36   }37 38   //SSE data39   private string SseData(string data)40   {41     return "data:" + data + "\n\n";42   }43 }

 

View

 1 @{ 2   Layout = null; 3 } 4  5 <!DOCTYPE html> 6  7 <html> 8 <head> 9   <meta name="viewport" content="width=device-width" />10   <title>Index</title>11 </head>12 <body>13   <div id="container"> 14   </div>15   <script>16     if (typeof (EventSource) !== "undefined")17     {18       var container = document.getElementById("container");19       var es = new EventSource("/home/sse");20       es.onopen = function (event) {21         container.innerHTML += "open<br/>";22       }23       es.onmessage = function (event) {24         container.innerHTML += event.data + "<br/>";25       };26       es.onerror = function (event) {27         container.innerHTML += "error<br/>";28         es.close();29       }30     }31     else32     {33       console.log("一边儿玩儿去");34     }35   </script>36 </body>37 </html>

运行如下:

[ASP.NET MVC] Real

 




原标题:[ASP.NET MVC] Real

关键词:ASP.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

tiktok安卓版怎么下载:https://www.goluckyvip.com/tag/82606.html
tiktok点赞1m是多少:https://www.goluckyvip.com/tag/82608.html
国外版tiktok怎么带货:https://www.goluckyvip.com/tag/82609.html
退货政策:https://www.goluckyvip.com/tag/8261.html
如何入驻tiktok:https://www.goluckyvip.com/tag/82610.html
国际版tiktok如何下载:https://www.goluckyvip.com/tag/82611.html
​TikTok发生了什么?美区增长首次停滞,准入管理力度加大:https://www.kjdsnews.com/a/1836407.html
2024年如何找到在TikTok上发帖的最佳时间:https://www.kjdsnews.com/a/1836408.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流