Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top