Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do server-sent events work with ASP.NET MVC?

I have an ASP.NET MVC application and I am using server-sent events. The application works fine but I am having some questions on how it works. Below is the controller code.

public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            ViewBag.Message = "SSE WITH ASP.NET MVC";
            return View();
        }
        public ActionResult Message() 
        {
          var result = string.Empty;
          var sb = new StringBuilder();
          sb.AppendFormat("data: {0}\n\n", DateTime.Now.ToString());
          return Content(sb.ToString(), "text/event-stream");

      }
    }

And below is the view code.

<script>

    function contentLoaded() {
        var source = new EventSource('home/message');
        //var ul = $("#messages");
        source.onmessage = function (e) {

            var li = document.createElement("li");
            var returnedItem = e.data;
            li.textContent = returnedItem;
            $("#messages").append(li);
        }
    };

    window.addEventListener("DOMContentLoaded", contentLoaded, false);
</script>
<h2>@ViewBag.Message</h2>
<p>
    SSE WITH ASP.NET MVC
</p>
<ul id="messages">
</ul>

My questions are: 1. The time gets updated only every 3 seconds. Why is it so? 2. How to determine how often the controller action will be called?

like image 222
ckv Avatar asked Dec 26 '22 20:12

ckv


1 Answers

The time gets updated only every 3 seconds. Why is it so?

Because your Controller is returning the ActionResult containing a single data and then closing the connection, so the browser waits 3 seconds and then re-opens it.

How to determine how often the controller action will be called?

The same way you would determine how often any other method will be called, with loops and delays.

SSE is Server Sent Events, you manage all this stuff from the server side, it'll only work properly if you explicitly hold the connection open, otherwise you may as well do AJAX polling from the client instead.

like image 72
robertc Avatar answered Dec 28 '22 10:12

robertc