Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading json string from socket

Tags:

java

c#

sockets

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

like image 785
Ahmed Avatar asked Feb 17 '26 03:02

Ahmed


1 Answers

if you remove Formatting.Indented, every buffReader.readLine() will return you a different(complete) json. Move your deserialization code into the while loop.

like image 155
L.B Avatar answered Feb 19 '26 15:02

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!