【发布时间】:2016-02-02 15:22:14
【问题描述】:
我正在使用本教程构建使用蓝牙进行连接的多人游戏:
https://developer.android.com/samples/BluetoothChat/index.html
由于我发送的是 JSON 格式的长字符串(长度为 5500+),因此消息处理程序方法不会返回我发送的整个字符串,而是将它们拆分为 989 个字符长的字符串(其长度始终为 989 个字符) )。问题是,当我尝试解析 JSON 字符串时,显然会引发错误,因为文本不完整。当我在控制台中打印出字符串时,它会将它们打印成由 989 个字符分割的多行。
另外请注意,缓冲区长度设置为 1024,但是当我增加限制时,结果不会有所不同,并且始终是 989 个字符。
byte[] buffer = new byte[1024];
知道发生了什么吗?这是消息处理程序方法。请注意,从主机设备发送的消息看起来很好(它没有拆分),但是当客户端收到它时,它会拆分成多个字符串。
private static final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
case BluetoothService.STATE_CONNECTING:
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
break;
}
break;
case BluetoothService.MESSAGE_WRITE:
// BYTE LENGTH IS OK IN HERE!
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
break;
case BluetoothService.MESSAGE_READ:
// BYTE LENGTH IS 1024 IN HERE!
byte[] readBuf = (byte[]) msg.obj;
message = new String(readBuf, 0, msg.arg1);
break;
}
}
};
【问题讨论】:
标签: java android bluetooth buffer