Android 中通过蓝牙连接丢失字节
我在 Android 设备 (Gingerbread 2.3.1) 和 PC 之间通过蓝牙连接丢失字节时遇到一些问题。我接收数据的方式是在 2 字节缓冲区中。所接收的值是在几分钟内从 PC 流式传输的(值代表波形)。这里只是一些代码片段,以便您可以理解。我的代码的基础来自 android 蓝牙聊天示例代码。
BluetoothSocket socket;
…………
mmInStream=socket.getInputStream;
对
byte[] buffer= new byte[2];
有人
bytes = mmInStream.read(buffer);
这种事情有疑问吗?丢失的字节似乎是随机发生的,而在其他时间接收到的值则符合预期。我使用 2 字节缓冲区,因为我收到的值是 16 位有符号整数。从 PC 端来看,我使用 RealTerm 发送数据的二进制文件。
我的缓冲区是否太小而导致字节丢失?
谢谢
I am having some issues with bytes being dropped over a bluetooth connection between an android device (Gingerbread 2.3.1) and a PC. The way I receiving the data is in a 2 byte buffer. The values being received is streaming from the PC over a few minutes (values represent a waveform). Here are just a few snippets of code so you can get the idea. The base of my code is from the android bluetooth chat sample code.
BluetoothSocket socket;
...
mmInStream=socket.getInputStream;
...
byte[] buffer= new byte[2];
...
bytes = mmInStream.read(buffer);
Has anyone has issues with this type of thing? The dropped bytes seem to happen at random times while at other times the values received are as expected. I am using a 2 byte buffer because the values I am receiving are 16 bit signed integers. From the PC side of things I am using RealTerm to send the binary files of data.
Is it possible that my buffer is too small and that is causing the dropped bytes?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
跟进您的答案。您可以仅使用计数器来记住已读取的字节数并将其与所需的数字进行比较,并将其用于索引以写入下一个字节。请参阅 http://www.yoda.arachsys.com/csharp/readbinary 中的 C# 版本。 html
Following up to your answer. You could just use a counter to remember how many bytes already read and compare it to the number wanted and also use it for the index to write the next byte(s). See a C# version at http://www.yoda.arachsys.com/csharp/readbinary.html
我已经找到问题所在了。我要感谢 alanjmcf 为我指明了正确的方向。
我没有通过
bytes
变量检查从mmInStream.read(buffer)
返回了多少字节。我只是期望返回的每个缓冲区都包含 2 个字节。我解决问题的方法是在从InputStream
返回buffer
后使用以下代码:这解决了我的问题。关于更好的方法有什么建议吗?
I have found what the issue is. I want to thank alanjmcf for pointing me in the right direction.
I wasn't checking by
bytes
variable to see how many bytes were returned from themmInStream.read(buffer)
. I was simply expecting that everybuffer
returned would contain 2 bytes. The way i solved the issue was with the following code after getting thebuffer
back from theInputStream
:This fixed my problem. Any suggestions on a better methodology?