2

我正在尝试为 Android 编写一个在两部手机之间交换数据的应用程序。(Android 4.2.1 和 4.4.2)作为基础,我使用了 android 教程部分中的 BluetoothChat 示例。我的问题是:当写入大量数据(>1kB)时,接收方经常得到错误的数据。有时它接收看似无关的数据,通常它接收许多连续 0 的部分,或者有时它甚至接收以前在同一消息中接收到的部分。

处理传输的方式如下:首先我发送一个 4 字节的头,它提供了以下消息的长度和它的消息类型(只是一个字节,指示程序如何理解消息)然后是实际的消息.

我使用了 BluetoothChat 中的 ConnectedThread,但实现为 AsyncTask,否则它与接收完全相同,处理如下:(如上所述)

  //code inside the doInBackground() section, and enclosed in a while + try block
  byte[] header = new byte[4];
  inputStream.read(header);
  int messagelength = readHeader(header);  // readHeader is the function that analyzes the 4 bytes header
  byte[] message = new byte[messagelength]; 
  inputStream.read(message); // read exactly that amount of bytes
  readMessage(message); // this function takes the byte[] and transfers it into whatever is needed.
                        // in this example simply calling new String(message) and printing to the Log

发送方完全相同

write(byte[] bytes) {
    outputStream.write(bytes); // I excluded the try/catch here
}

测试多个字符串并通过简单地调用 string.getBytes() 进行转换,结果:

130字节字符串被​​正确传输,

1443 字节字符串被​​正确传输,

51948 字节字符串在大约 900 字节后失败。日志将正确写入字符串,直到它只打印奇怪的“菱形问号” - 符号。

但是,失败的时刻是可变的。

outputStream.write(bytes) 可以处理多少字节有限制吗?有人知道为什么通过 Streams 简单地发送字节会失败吗?一些内部缓冲区问题?也许是一个循环缓冲区(因为有时旧的消息部分会重复)?

非常感谢您的帮助,由于这个问题,我已经浪费了几个小时(尝试编写和阅读较小的块,但这并没有太大帮助)

4

0 回答 0