Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  67] [ 5]  / answers: 1 / hits: 17408  / 9 Years ago, mon, february 23, 2015, 12:00:00

check my code below, Here I have added three alert messages to each event type, but in this code source.onopen()[alert: readyState: 1] and source.onerror()[alert: readyState: 0] works properly but in case of onmessage() it is not executed.`



       if(typeof(EventSource) !== undefined) {
var source = new EventSource('clinic/get');
source.onopen = function(){
alert('connection is opened.'+source.readyState);
};

source.onerror = function(){
alert('error: '+source.readyState);
};

source.onmessage = function(datalist){

alert(message: +datalist.data);
};

} else {
document.getElementById(clinic-dtls).innerHTML = Sorry, your browser does not support server-sent events...;
}`


check the code below for the server side



Random random = new Random();
response.setContentType(text/event-stream);
response.setCharacterEncoding(UTF-8);
System.out.println(clinic/get got hit);

try {
Writer out = response.getWriter();
out.write(data: welcome data+random);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


I am using STS(Spring tool Suits), I am wondering, when I am using ctrl+space on EventSource (source) object, in the options it only shows onopen() and onerror(), where is the onmessage().



I will be highly appreciate, if I'd get any response. --Thanks


More From » java

 Answers
169

Solved it !!!



There is no issue with code, the actual issue is when I am writing response to client my response message should look like as below.



PrintWriter out = response.write(data: message+value+nn);
out.flush(); //don't forget to flush


In my code I was missing the last part nn in response object so source.onmessage(datalist) in javascript didn't get hit.



Crazy coding..


[#67709] Friday, February 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jananauticat

Total Points: 1
Total Questions: 105
Total Answers: 95

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;