Jae
Jae

Reputation: 173

InputStream.read method getting called too fast

I'm trying to read InputStream data from Bluetooth socket and the method does what it suppose to do at the beginning. But for some reason later on it doesn't read everything.

Here's the method that I'm using right now:

public int read(byte[] b, int off, int len)

When I check the byte array its end part is the beginning of the next part of data. Which means the read method got called again even before it finished reading. Does anyone know how to handle this problem?

Upvotes: 2

Views: 593

Answers (1)

Stephen C
Stephen C

Reputation: 718708

You are going to have to deal with this yourself in your application protocol design.

Assuming that you are using Android BluetoothSocket with RFCOMM, the javadoc says this:

RFCOMM is a connection-oriented, streaming transport over Bluetooth.

and

The interface for Bluetooth Sockets is similar to that of TCP sockets:

While it is not crystal clear from these quotes, the implication is that the streams will behave like TCP streams, and that means that there are no reliably discernible message / packet / records boundaries in the bytes deliver by the read methods. If the sender decides to send two messages back-to-back, then the receiver is liable to get the end of one message and the beginning of the next one in the read buffer.

So ... if you have a message / packet oriented application protocol running over the socket, you have to design your application protocol so that the message boundaries are discernible by the receiver irrespective of how few / many bytes come through at a time. In other words, you need to use packet byte counts, end-of-packet markers or some-such in your protocol to allow the receiver to figure out where each packet ends and the next one begins.

Upvotes: 5

Related Questions