Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in EventSource

I'm trying to make a page that uses the EvenSource object (in javascript) to make an Server-Sent Event (comet). I read many tutorials about it and haven't found one that explains the following questions:

  1. When i subscribe to the "onerror" event of the EventSource - what is the type of the parameter i get? How do i know exactly what was the error?

  2. I know that EvenSource has a readystate and that it changes depend on the browser. Why is my readystate changes to 0 after each "onmessage" event occurs? (i use chrome).

  3. How do i prove that my connection to the server stays connected and not reconnect every time?

Browser: Chrome.

Server Side: Java (if it's relevant the example i made is in Java EE preview. But i'm going to work on WebLogic 10R3.

What happens in my example is that the data is being sent from the server to the client, than the "onerror" event occurs (readystate is 0) and after 3 seconds (default for chrome) it reconnects and sends the data again.

The javascript code:

var source = new EventSource("TrySRV");
source.onmessage = function(event){
    alert(event.data);
}

source.onerror = function(event){
    alert(source.readystate);
}

The Java code:

response.setHeader("Content-Type", "text/event-stream");
response.setHeader("Cache-Control", "no-cache");
response.getWriter.write("Hello World");

If there's anything else missing that you wish to know - tell me. Hope you'll be able to help me.

Thanks!

like image 568
dotanlaks Avatar asked Aug 29 '12 22:08

dotanlaks


2 Answers

You need to hold the connection on server, instead of responsing on it and closing.

Please see http://jcp.org/en/jsr/detail?id=315, or Glassfish / Grizzly / Jetty servers.

like image 123
Ilya Kantor Avatar answered Sep 28 '22 01:09

Ilya Kantor


try using:

response.getWriter.write("data:Hello World")

According to w3schools: Output the data to send (Always start with "data: ")

http://www.w3schools.com/html/html5_serversentevents.asp

like image 39
Tiago PC Avatar answered Sep 28 '22 01:09

Tiago PC