EventSource onmessage() is not working where onopen() and onerror() works properly?
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+"\n\n");
out.flush(); //don't forget to flush
In my code I was missing the last part "\n\n" in response object so source.onmessage(datalist)
in javascript didn't get hit.
Crazy coding..
I think the correct formatting is:
out.write("event: message\n");
out.write("data:" + value + "\n\n");
The onmessage
handler assumes the event name is message
. If you want to use other event names, you can subscribe to them using addEventListener
.