Currently I am writing data in JSON format, one message at a time like this:
String[] arr = strLine.split(",");
out.append("data: {\n");
out.append("data: \"c1\": " + arr[0].toString()+ ",\n");
out.append("data: \"c2\": " + arr[1].toString()+ ",\n" );
out.append("data: }\n\n");
out.flush();
But, now I want to out.flush only when 5 such messages are there. So, how do I do this? create Json messages? with separate data:{ } body. And if I do so how do I access pairs of c1, c2 at client side with javascript? And what are the alternatives.
PS: When I say 5 values, I mean 5 pair of values of c1 and c2.
And how do I access values using javascript at client side, if I do something like this
out.append("data: [\n");
for(int j=0; j<5; j++) {
String[] arr = strLine.split(",");
if (j!=0) out.append(",\n");
out.append("\{"c1\": " + arr[0].toString()+ ",\n");
out.append(\"c2\": " + arr[1].toString()+"}" );
out.flush();
}
//HEY MR, LOOK BELOW ME
//HEY MR, LOOK BELOW ME
//HEY MR, LOOK BELOW ME
//HEY MR, LOOK BELOW ME
out.append("]\n"); <---- HEY RIGHT HERE
//HEY MR, LOOK ABOVE ME
//HEY MR, LOOK ABOVE ME
//HEY MR, LOOK ABOVE ME
//HEY MR, LOOK ABOVE ME
out.flush();
Working JS code as requested ( calling registerSSE() on body load):
function registerSSE(){
var source = new EventSource ('http://localhost:8080/SSE_Test1/ReadCsv');
source.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
console.log(data.timestamp, data.c1, data.c2, data.c3, data.c4);
}
And in servlet you just need to append this line:
response.setContentType("text/event-stream");
Please don’t manually generate/parse JSON strings. In Java, use org.json and in Javascript, use
JSON.parseandJSON.stringify.MDN: parse and stringify
For outputting pairs of 5, you’d do something like:
To access it on the client side, given your EventSource
source: