Android BluetoothSocket OutputStream write blocks infinitely
Asked Answered
C

1

6

I need to programmatically write data of say 1 to 100 MB in chunks of 1024 bytes to the remote Bluetooth device. Both are android devices. Here is a sample code snippet in my client program to transfer data –

bTSocket.connect(); //connect to remote BT device
DataOutputStream outStream = new DataOutputStream(bTSocket.getOutputStream());
byte[] buffer = new byte[1024];
int bytesToTransfer = 1000000;
while (bytesToTransfer > 0) {
    outStream.write(buffer);
    outStream.flush();
    bytesToTransfer -= 1024;
}
outStream.close();

While running this piece of code on Android 2.2(Froyo), it works fine. However in case of Android 2.3.4 and 4.0.4, outStream.write(buffer) blocks infinitely after transfer of some data (say of 100 KB). Worth mentioning, the remote device is not configured for listening data. Is there any limitation on the amount of data that can be written?

Candra answered 10/9, 2012 at 15:17 Comment(2)
Are you saying the other side is not reading data from the socket?Frail
Precisely, the server is not configured to read data over the stream.Candra
T
6

The Bluetooth socket operates in blocking mode for both reads and writes.

If you fill up the send buffer, then the only thing that .write() can do to stop you trying to send any more data is to block. The alternative to it blocking would be to return an "operation would block!" error code, just like TCP sockets can do when placed in non-blocking mode. But the Bluetooth socket doesn't provide any such non-blocking mode.

You state that the remote Bluetooth device is not reading from its socket. With this being the case, the local sending buffer and remote receive buffer, with each only being of a certain finite size, will eventually fill up. At this point, your .write() operation is going to block until the remote end reads something from its socket. You can't just keep pumping in megabytes of data and expect it to just buffer it all somewhere.

The differences you experience between different Android platforms are probably down to the different amounts of buffer space available in the related Bluetooth stacks.

Tweet answered 10/9, 2012 at 17:30 Comment(1)
@Tweet Thanks for information. I never faced a long time blocking issue even when i tried to write thousands of Kilobytes. Tho i still wonder what the buffer size is (using Android 2.3.3).Brianbriana

© 2022 - 2024 — McMap. All rights reserved.