1
votes

I am trying to utilize server sent events to handle the client side of some async operations im doing server side. Scroll to the bottom to see the final question.

What I have is an web app that needs a global search. The returns can be massive and take some time as they are actually sent to a webservice and then returned as XML.

I am trying to use server sent events (javascript: EventSource) to enable this. It works great for just one event but if I want to do a bunch of different events it gets a little weird, at least for me. I am new to SSE.

so far I have done this:

var sse = new EventSource('testsse.aspx');

function init() {
            sse.onopen = function (e) {
                console.log(e.data);
            };

            sse.onmessage = function (e) {
//if data has been returned the "data:" field will not be empty so we know the server operation is complete. 
                if (e.data.length>0) {
                    $('#rgCcr').kendoGrid({
                        dataSource: JSON.parse(e.data)
                    });
                    sse.close();
                }
                    console.log("message: " + e.data);
            };

$(document).ready(function() {
    init();
});

on the server I have an aspx page that is building the json strings. as I mentioned I have it working great if I just use the standard "data: my message\n\n" format. What I need to do is get a few more pieces of info in there.

The spec for SSE says that you can specify an event to fire. I cant get this to work so far though.

in my aspx I am building the string like this:

json = string.Format("id:{0}\n event:myEvent\n data:{1}\n\n", id, ser.Serialize(ccrData));

I have tried creating a custom event but I am not sure what to bind it to in order to catch it.

On the page I have 5 different areas that are being search as part of the global search. Each is executed as an async task on the server and as they complete they will send the data back to the client. once the client detects the event has submitted data it will close the listener and add the data results to the kendo grid.

How can I use the event field of the SSE to tell the difference between what is coming back?

1
Not an answer, but signalr.net wouldn't solve your problem?Rudy

1 Answers

1
votes

Rather than using the "onmessage" function, you could try registering an event listener. That way you can choose to listen to a particular event type.

es = new EventSource('/events', withCredentials: true);

es.addEventListener("open", function (e) {
  alert("Connecting...");
});

es.addEventListener("error", function (e) {
  alert("Error");
});

es.addEventListener("myEvent", function (e) {
  alert("MyEvent");
  alert(e.data);
});

There's great documentation here: http://html5doctor.com/server-sent-events/