I have a simple client/server application that need to send some JSON objects (that are generated at runtime) through socket to the server.
On the client I have (for test purposes): drawList is a list of Draw objects (with 4 elements).
Socket client = new Socket(serverName, serverPort);
Gson gson = new Gson();
DataOutputStream out = new DataOutputStream(client.getOutputStream());
for (int i=0; i<drawList.size(); i++){
out.writeUTF(gson.toJson(drawList.get(i)));
out.flush();
}
out.close();
client.close();
On the server side I have:
Socket server = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
List<Draw> drawList = DrawUtils.getDrawList(inputLine);
for (Draw draw : drawList){
processDraw(draw);
}
}
Follows the getDrawList method
public static List<Draw> getDrawList(String input){
List<Draw> drawList = new ArrayList<Draw>();
Gson gson = new Gson();
JsonParser jParser = new JsonParser();
JsonArray jArray = jParser.parse(input).getAsJsonArray();
for (JsonElement obj : jArray){
drawList.add(gson.fromJson(obj, Draw.class));
}
return drawList;
}
The points here are two:
Even if I'm flushing the output channel on client for each "Draw object", at server side I'm getting only one big String with all my objects. Maybe at this point I'm missing some socket concept...
Since I'm getting all my objects in one string, I'm trying then to parse it as a Json array, but I'm getting an exception "com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON". Using debugger I checked the input String and it seems ok except for a strange "A" separating my objects.
Any clues? Thanks!