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

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

问题描述

我需要编程写说,1到100 MB的数据在1024字节的块到远程蓝牙设备。两者都是Android设备。这里是我的客户端程序来传输数据的样本code片段 -

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)code,它工作正常。然而,在案件的Andr​​oid 2.3.4和4.0.4,outStream.write(缓冲)块的一些数据传送后无限的(例如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()能做些什么来阻止你尝试发送更多的数据是阻止。另一种方法来阻止它会返回一个操作会阻止!错误code,就像当置于非阻塞模式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.

您不同的Andr​​oid平台之间经历的差异可能下降到不同数量的缓冲空间,可以在相关的蓝牙堆栈。

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

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

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