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:
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?
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).
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With