[ASP. net mvc] Real-time HTML5 server send event (server-sent event), html5server-sent
If you have time recently, I plan to take a look at SignalR. By the way, let's take a look at Server Sent Events.
Controller
The output data format is data: [data] \ n. It's okay to try to output more than 8000 characters. The limit is not enough. However, if the data also contains \ n, the data will be truncated.
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 // set the http mime type, page 15 Response not cached. 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,500 0); 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 "; 42} 43}
View
1 @ {2 Layout = null; 3} 4 5 <! DOCTYPE html> 6 7
Run the following command: