Server-Sent Events via MVC, get simultaneously result and error

ε祈祈猫儿з 提交于 2019-12-25 16:46:25

问题


I tried to get SSE technology and couldn't resolve one trouble. Always triggered two event onmessage and error. I have getting valid date and simultaneously error message. Why this happening and how to resolve this ? How to prolong live time of connection "polltransport request" ??

Here server side

  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();
            }
        }

Here client 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..');
    }

});

Here screens of console log and network tabs in google chrome browser


回答1:


Your server-side code needs to continually write to the Response object instead of returning a result:

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

Returning a result closes the connection, which triggers the EventSource.onerror.

See here for some more details.



来源:https://stackoverflow.com/questions/22043254/server-sent-events-via-mvc-get-simultaneously-result-and-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!