最近有时间,打算看看SignalR,顺便了解一下Server Sent Events。
Controller
输出的数据格式为:data:[数据] 。输出的数据尝试8000多字符也没问题,具体的上限就没试了。但是如果数据里也包含 的话,数据就会被截断。
1 public class HomeController : Controller 2 { 3 // GET: Home 4 public ActionResult Index() 5 { 6 return View(); 7 } 8 9 //Server-Sent Event 10 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 try 21 { 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 data 39 private string SseData(string data) 40 { 41 return "data:" + data + " "; 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 else 32 { 33 console.log("一边儿玩儿去"); 34 } 35 </script> 36 </body> 37 </html>
运行如下: