CodePrimate
CodePrimate

Reputation: 6666

InputStream.read() is either missing or adding a value in my buffer - How come?

I've created the following procedure in the run() method of the ConnectedThread taken from the BluetoothChat sample.

// Read from the InputStream
byte[] buffer = new byte[16];
int offset = 0;
while(buffer.length-offset != 0)
{
    int bytesRead += mmInStream.read(buffer, offset, buffer.length-offset);
    offset += bytesRead;
}
// Do stuff with the contents of the buffer

The buffer is loaded in with 16 bytes gradually as expected but for some reason at the 10th byte in the array a 0 is inserted and shifts the remaining part of the package(and as such corrupting the entire package)

Here is an example of what is happening

The following is sent from the other client :

[-11, 126, -16, -30, -92, 110, -26, 13, 22, 91, -31, 32, 54, -125, -112, 45]

This is what I receive :

[-11, 126, -16, -30, -92, 110, -26, 13, 22, 91, 0, -31, 32, 54, -125, -112]

As you can see, an extra 0 is pushed in as the 10th byte and the rest of the package is shifted to the right(cutting off the last byte)

As part of the debugging process we tried having a breakpoint at bytesRead += mmInStream.read(buffer, offset, buffer.length-offset) and to our surprise the entire original message was received. What gives?

How does the "break" in reads correct this issue? What am I doing wrong or not understanding?

Upvotes: 2

Views: 698

Answers (2)

user207421
user207421

Reputation: 310850

Throw it all away and use DataInputStream.readFully().

Upvotes: 0

stefank
stefank

Reputation: 101

Probably you meant

bytesRead = mmInStream.read(buffer, offset, buffer.length-offset);
offset += bytesRead;

instead of

bytesRead += ...

Upvotes: 3

Related Questions