Stashi
Stashi

Reputation: 71

InputStream reads available data in more than 1 try

I have two applications. Connected to each other over wifi. I am using InputStream to read data sent from server app. The code is std one,

try {                   
        bytesRead = mmInStream.read(buffer, 0, 6300);//read(buffer);        
        Logger.d(TAG, "Bytes read from inStream : "+bytesRead);                             
        if (-1 != bytesRead) {
        handler.obtainMessage(12, bytesRead, -1, buffer).sendToTarget();
        } else {
        connectionLost();
        }
    } catch (Exception e) {
        e.printStackTrace();
       connectionLost();
   }

Killing and resetting threads in connectionLost method. I am sending close to 6kb data from server app, in a JSON String. This works 3 out of 5 times.

Sometimes the read will return say, 1.5kb buffer and in second run it will give rest of data. But meanwhile first 1.5 is sent to JSON parser and that gives me error. I printed bytes written to outputBuffer from server side. it will write 6k bytes every time. I want to know why at sometime, read() method reads only half of stream and rest of it in second try?

How do i know if it has read total data or only half of it? i dont know before hand how many bytes server will send. (I came up with number because i am debugging the code. that 6k may change later).

Thank you in advance. Stuck at this issue for two days. :(

Upvotes: 1

Views: 159

Answers (1)

Henry
Henry

Reputation: 43738

It works as designed. When you read a stream, you are not guaranteed to get all available bytes in one go. Most likely they are not even available when you do the first read.

You need some programmatic ways to find out if a message is complete. For example if it is a JSON object or array, you will notice if it is complete or not by analysing what you got. Another way would be to transmit the length of the message.

Upvotes: 1

Related Questions