服务器发送的事件如何与ASP.NET MVC一起使用? [英] How do server-sent events work with ASP.NET MVC?

查看:104
本文介绍了服务器发送的事件如何与ASP.NET MVC一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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");

      }
    }

以下是查看代码。

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

我的问题是:
1.时间每3秒更新一次。为什么会这样?
2.如何确定调用控制器操作的频率?

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?

推荐答案


时间每3秒更新一次。为什么会这样?

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

因为你的控制器正在返回 ActionResult 包含单个数据然后关闭连接,因此浏览器等待3秒,然后重新打开它。

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是服务器已发送事件,您从服务器端管理所有这些内容,只有在您明确保持连接打开时它才能正常工作,否则您也可以而是从客户端进行AJAX轮询。

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.

这篇关于服务器发送的事件如何与ASP.NET MVC一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆