Reputation: 15069
I have java server that I am writing the server reads command from clients,
the client written in C# sends command via socket in the form of json string. The command looks like this
{
"command": "blah",
"key1": "value1",
"key2": "value3",
"key3": "value4",
}
The json string could have different number of key-val pairs every time, so there is no static count as such to measure number of lines in json command.
Here is how C# client sends json string to java server
String json = JsonConvert.SerializeObject(map, Formatting.Indented);
streamWriter.WriteLine(json);
streamWriter.Flush();
I want to read json this in the java code written in android. it looks something like as shown below, it reads the json lines properly but it blocks after reading last line of json command I am not sure what is the decent way to know that command has ended ..
serverSocket = new ServerSocket(4444);
clientSocket = serverSocket.accept();
InputStream inStream = clientSocket.getInputStream();
InputStreamReader inStreamReader = new InputStreamReader(inStream);
BufferedReader buffReader = new BufferedReader(inStreamReader );
String input = "";
while((input = buffReader.readLine())!= null)
{
command += input;
}
//Does not get to this point, blocks above on the readLine after reading full json..
JSONObject jsObj = new JSONObject(input);
Object ovj = jsObj.get("command");
I know may be I can send number of lines before sending json and read that many times in a while loop ? but that looks like a dirty solution, please advise what's the right way to do it.
Thanks, Ahmed
Upvotes: 3
Views: 6801
Reputation: 116168
if you remove Formatting.Indented
, every buffReader.readLine()
will return you a different(complete) json. Move your deserialization code into the while loop.
Upvotes: 1