通过MVC发送服务器发送的事件,同时获得结果和错误

时间:2014-02-26 13:44:35

标签: javascript asp.net asp.net-mvc html5 server-sent-events

我试图获得SSE技术并且无法解决一个问题。始终触发两个事件onmessage和错误。我收到了有效的日期和错误消息。为什么会这样,以及如何解决这个问题?如何延长连接的实时时间“polltransport request”??

服务器端

  public class HomeController : Controller
        {
            public ActionResult Message() 
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var serializedObject = ser.Serialize(new { item = "fuck", message = "hello" });
                var sb = new StringBuilder();
                sb.AppendFormat("data: {0}\n\n", serializedObject);

                return Content(sb.ToString(), "text/event-stream");
            }

            public ActionResult SEEIndex()
            {
                return View();
            }
        }

这里是客户端javascript

$(document).ready(function () {

    var serverSentEvents = new window.EventSource('/Home/Message');  //home/message   /api/Event

    serverSentEvents.onmessage = function (e) {
        //$("#messages").append(e.data.item + '<br />');
        var data = JSON.parse(e.data);
        console.log('Yes! We get it, here is you data', data.item);
    };

    serverSentEvents.onerror = function (e) {
        console.log('error');
    };

    if (typeof (window.EventSource) !== "undefined") {
        console.log('Yes! Server-sent events support!');
    }
    else {
        console.log('Sorry! No server-sent events support..');
    }

});

这里是Google Chrome浏览器中console lognetwork标签的屏幕

1 个答案:

答案 0 :(得分:1)

您的服务器端代码需要不断写入Response对象而不是返回结果:

using System.Threading;

public class HomeController : Controller {
    public ActionResult SEEIndex() {
        return View();
    }
    public void Message() {
        Response.ContentType = "text/event-stream";
        do {
            Response.Write("data: understandably\n");
            Response.Write("data: frustrated\n");
            Response.Write("\n");     //double newline signals the end of an event
            Response.Flush();
            Thread.Sleep(2000);       //wait 2 seconds before writing again
        } while (true)
    }
}

返回结果会关闭连接,从而触发EventSource.onerror

有关详细信息,请参阅here