2

I am trying to write an App for Android that exchanges data in between 2 phones. (Android 4.2.1 and 4.4.2) As a basis I used the BluetoothChat example from the android tutorial section. My problem is this: when writing larger amounts of data (>1kB) the receiving side often gets the wrong data. Sometimes it receives seemingly unrelated data, often it receives sections of many consecutive 0s, or sometimes it even receives parts that where received before in the same message.

The way the transmissions are handled is as follows: First I send a 4 byte header, which provides the length of the following message and it's messagetype (just a single byte indicating how the message is to be understood by the program) Then the actual message.

I used the ConnectedThread from the BluetoothChat but implemented as an AsyncTask, otherwise it is exactly the same apart from the receiving which is handled as follows: (and as mentioned above)

  //code inside the doInBackground() section, and enclosed in a while + try block
  byte[] header = new byte[4];
  inputStream.read(header);
  int messagelength = readHeader(header);  // readHeader is the function that analyzes the 4 bytes header
  byte[] message = new byte[messagelength]; 
  inputStream.read(message); // read exactly that amount of bytes
  readMessage(message); // this function takes the byte[] and transfers it into whatever is needed.
                        // in this example simply calling new String(message) and printing to the Log

The sending side is exactly the same

write(byte[] bytes) {
    outputStream.write(bytes); // I excluded the try/catch here
}

Testing multiple Strings and converting by simply calling string.getBytes(), resulted in:

130 byte String being transmitted correctly,

1443 byte String being transmitted correctly,

51948 byte String failing after about ~900 bytes. the Log would write the String correctly up until a point where it would only print the weird "question mark in a diamond" - symbol.

The moment of failure is variable though.

Is there a limit to how many bytes the outputStream.write(bytes) can handle? Has someone got an idea why this simple sending of bytes through Streams can fail? Some internal buffer problems? Maybe a cyclic buffer (as sometimes old message parts got repeated)?

Thank you very much for the help, I've lost hours due to this issue (tried writing and reading smaller chunks, but that didn't help a lot)

edi
  • 21
  • 1
  • In the meantime I did find a way to get it working, simply by reading what is available, rather using inputStream.read(buffer), but I still don't understand why the first approach doesn't work. Code: `int available = inStream.available(); if (available > 0) { byte[] buffer; inStream.read(buffer); }` – edi Apr 15 '14 at 15:24

0 Answers0