EventSource onmessage() is not working where onopen() and onerror() works properly?
java, javascript
Solution
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..
Problem
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