Android BluetoothSocket OutputStream 无限写入块 [英] Android BluetoothSocket OutputStream write blocks infinitely

查看:28
本文介绍了Android BluetoothSocket OutputStream 无限写入块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式将 1 到 100 MB 的数据以 1024 字节的块写入远程蓝牙设备.两者都是安卓设备.这是我的客户端程序中传输数据的示例代码片段 –

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();

在 Android 2.2(Froyo) 上运行这段代码时,它运行良好.然而,在 Android 2.3.4 和 4.0.4 的情况下,outStream.write(buffer) 在传输一些数据(比如 100 KB)后无限阻塞.值得一提的是,远程设备没有配置监听数据.可写入的数据量有限制吗?

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?

推荐答案

蓝牙套接字在读取和写入的阻塞模式下运行.

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

如果你填满了发送缓冲区,那么 .write() 唯一能阻止你尝试发送更多数据的事情就是阻塞.它阻塞的替代方法是返回操作会阻塞!"错误代码,就像 TCP 套接字在处于非阻塞模式时所做的那样.但是蓝牙套接字不提供任何这种非阻塞模式.

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.

您声明远程蓝牙设备未从其套接字读取数据.在这种情况下,本地发送缓冲区和远程接收缓冲区(每个缓冲区的大小都只有某个有限大小)最终将填满.此时,您的 .write() 操作将阻塞,直到远程端从其套接字读取某些内容.您不能只是不断地抽取数兆字节的数据,并期望它只是在某个地方缓冲所有数据.

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.

您在不同 Android 平台之间体验到的差异可能归结于相关蓝牙堆栈中可用的缓冲区空间量不同.

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

这篇关于Android BluetoothSocket OutputStream 无限写入块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆