最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add a JSON Array to the return of a Server Side Event - Stack Overflow

programmeradmin1浏览0评论

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");

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");
Share Improve this question edited Sep 4, 2014 at 3:09 JasonMArcher 15k22 gold badges59 silver badges53 bronze badges asked Oct 8, 2012 at 18:33 Andy897Andy897 7,13312 gold badges56 silver badges92 bronze badges 18
  • Hi Shusl, No this is java code in my servlet. I writing data in json format in servlet and trying to read it at client side using javascript. Hope I answered what you are asking :) – Andy897 Commented Oct 8, 2012 at 18:37
  • I should have at first place, thank You ! – Andy897 Commented Oct 8, 2012 at 18:39
  • 5 The heck? Just use a library. – Anders Commented Oct 8, 2012 at 18:39
  • Can you use something like socketio-java to send the data in bursts? Because, clients can't just spontaneously be given data from the server, they have to ask the server for data. Otherwise, why are you writing your own JSON output class in java? If you can't find one, try these guys: json/java There's no need to roll your own poor JSON emitter. – jcolebrand Commented Oct 8, 2012 at 18:39
  • Don't write JSON by hand, use a library from json/java – Ruan Mendes Commented Oct 8, 2012 at 18:40
 |  Show 13 more ments

2 Answers 2

Reset to default 8

Please don't manually generate/parse JSON strings. In Java, use org.json and in Javascript, use JSON.parse and JSON.stringify.

MDN: parse and stringify

For outputting pairs of 5, you'd do something like:

String[] arr = strLine.split(",");
JSONArray array = new JSONArray();
for(int i=0, j=0;i<arr.length;i+=2,j++){
   JSONObject dataObj = new JSONObject();
   dataObj.put("c1", arr[i]);
   dataObj.put("c2", arr[i+1]);
   array.put(j, dataObj);
   if ((j > 0) && (j % 5 ==0)) {
       out.append("data: " +array.toString() + "\n");
       out.flush();
       array = new JSONArray(); // start with a new one
   }
}

To access it on the client side, given your EventSource source:

source.addEventListener('message', function(e) {
    var data = JSON.parse(e.data); // data is an array of {c1:...,c2:...} objects
    for (var i = 0; i < data.length; i++) { // it should be 5 in length
        console.log('c1 is: '+data[i].c1+' and c2 is '+data[i].c2);
    }
}

To access a JSON string in JavaScript, just do this:

var myJson = JSON.parse(myJsonString);
发布评论

评论列表(0)

  1. 暂无评论