front end
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h1>获得服务器更新</h1> <div id="result"></div> <script> if (typeof (EventSource) !== "undefined") { var source = new EventSource("/HTML5/tt"); source.onmessage = function (event) { document.getElementById("result").innerHTML += event.data + "<br />"; }; } else { document.getElementById ( "the Result") the innerHTML = "Sorry, your browser does not support server-sent events ...." ; } </ Script> </ body> </ HTML>
rear end
public class HTML5Controller : Controller { // // GET: /HTML5/ public ActionResult Index() { return View(); } public void tt() { Response.ContentType = "text/event-stream"; Response.Expires = -1; Response.Write("data: " + DateTime.Now.ToString() + "\n\n");//注意结束要两个\n Response.Flush(); } }