[ASP. net mvc] Real-time HTML5 server send event (server-sent event), html5server-sent

Source: Internet
Author: User

[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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.