FabiF
FabiF

Reputation: 2796

Android bluetooth chunk size

I'm experiencing a strange behavior of bluetooth socket (in my opinion), and I would like know if anybody can clarify it to me.


The situation:

I have two Android applications connected together by a Bluetooth socket:

On the reader side I use a buffer of 1024 bytes. The sender send a message a little bit larger than the receiver buffer size: 1024 + 108 bytes (always the same message).

Ok now the behavior:

On the reader app I receive the most often a first chunk of 1024 bytes which fills up the buffer (as expected) and then a second one of 108 bytes.

But really often (maybe 40% of the time) I receive a first chunk of 1008 bytes and then a second one of 124 bytes.


I really would like to understand this because I'm affraid to miss an important bluetooth concept. At first I was thinking to compare the count of byte read with the buffer size to know if the entire message had been received but this experimentation shows that it's maybe not a good idea.

Is anybody can explain to me this behavior?

Thanks in advance.

Upvotes: 3

Views: 2248

Answers (2)

Chris Moeller
Chris Moeller

Reputation: 33

I'm finding the same thing- it seems to be because Bluetooth sends data over as a stream instead of packets.

So if I send 4 500 byte packets, it might end up sending a 1600 byte one and a 400 byte one, or the way I sent it. Over stack overflow questions say to use some random value in the byte array to tell when a message is finished (How to read all bytes together via Bluetooth?).

There should be a better way, but I plan to use a very unlikely character set to try to find the end of the message- and pad it onto the end of each of my messages going out. Some of the other stack overflow questions suggest using '\n', but I might end up using several to make it more unlikely, such as: "\t~\t"- something that should never be typed in my game (or hopefully not extracted from the enormous amount of other stuff going on). Hope that helps!

Upvotes: 1

FabiF
FabiF

Reputation: 2796

For the record, I now use Google Guava methods for read/write on streams and all works fine.

Upvotes: 2

Related Questions