Wwwroot / index.html
When loading the page, create an EventSource for the URL http://www.somehost.ca/sse . Then write his events to the console.
<body> <script type="text/javascript"> var source = new EventSource('sse'); source.onmessage = function (event) { console.log('onmessage: ' + event.data); }; source.onopen = function(event) { console.log('onopen'); }; source.onerror = function(event) { console.log('onerror'); } </script> </body>
Middleware
Medium- sse software processes the sse path. It sets the Content-Type header to text/event-stream , which is required for the server socket event. It records the response flow without closing the connection. He imitates work, lingering for five seconds between spellings.
app.Use(async (context, next) => { if (context.Request.Path.ToString().Equals("/sse")) { var response = context.Response; response.Headers.Add("Content-Type", "text/event-stream"); for(var i = 0; true; ++i) {
controller
The controller does the same thing as middleware.
[Route("/api/sse")] public class ServerSentEventController { private readonly IHttpContextAccessor _httpContextAccessor; public ServerSentEventController( IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } [HttpGet] public async Task Get() { var response = _httpContextAccessor.HttpContext.Response; response.Headers.Add("Content-Type", "text/event-stream"); for(var i = 0; true; ++i) { await response .WriteAsync($"data: Controller {i} at {DateTime.Now}\r\r"); response.Body.Flush(); await Task.Delay(5 * 1000); } } }
Console output in Firefox
This is the result in the Firefox console window. Every five seconds, new messages appear.
onopen onmessage: Message 0 at 4/15/2016 3:39:04 PM onmessage: Message 1 at 4/15/2016 3:39:09 PM onmessage: Message 2 at 4/15/2016 3:39:14 PM onmessage: Message 3 at 4/15/2016 3:39:19 PM onmessage: Message 4 at 4/15/2016 3:39:24 PM
References:
Shaun luttin
source share