简体   繁体   English

服务器发送的事件如何与 ASP.NET MVC 一起使用?

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

I have an ASP.NET MVC application and I am using server-sent events.我有一个 ASP.NET MVC 应用程序,我正在使用服务器发送的事件。 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.我的问题是: 1. 时间每 3 秒更新一次。 Why is it so?为什么会这样? 2. How to determine how often the controller action will be called? 2. 如何确定控制器动作的调用频率?

The time gets updated only every 3 seconds.时间仅每 3 秒更新一次。 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.因为您的Controller返回包含单个数据的ActionResult然后关闭连接,所以浏览器等待 3 秒然后重新打开它。

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 .与您确定调用任何其他方法的频率相同,使用 loops 和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. SSE 是服务器发送的事件,您从服务器端管理所有这些东西,只有在您明确保持连接打开时它才能正常工作,否则您也可以从客户端进行 AJAX 轮询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM