我正在尝试在 Android 上通过蓝牙发送字节数组。我有一个服务器/客户端设置正在运行。我将日志详细信息(例如字符串和整数)从一个发送到另一个(双向工作)。现在我在程序中遇到了需要发送多个字节数组的情况。我的服务器首先发送与数组长度相对应的整数,然后发送字节[]。客户端通过读取 int 和读取数组来反射(reflect)这一点。第一个 int 正确发送,但之后客户端正在读取服务器似乎没有发送的大量 int 值。
这是我的服务器端代码:
case 25:
Log.d("CONSEQUENCES", "STARTING CODE 25");
while (true) {
ArrayList<byte[]> toSend = queue.take();
Log.d("CONSEQUENCES", "TAKEN IMAGES");
Log.d("CONSEQUENCES", "taken images size = " + toSend.size());
for (int i = 0; i < toSend.size(); i++){
Log.d("CONSEQUENCES", "item length = " + toSend.get(i).length);
oos.writeInt(toSend.get(i).length);
oos.flush();
oos.reset();
oos.write(toSend.get(i));
oos.flush();
oos.reset();
}
Log.d("CONSEQUENCES", "SENT IMAGES");
Log.d("CONSEQUENCES", "SENT images size = " + toSend.size());
}
以下是服务器端的日志:
这是客户端代码:
case 25:
while (true){
Log.d("CONSEQUENCES", "WAITING FOR IMAGES");
ArrayList<byte[]> received = new ArrayList<byte[]>();
for (int i = 0; i <25; i++){
int size = ois.readInt();
Log.d("CONSEQUENCES", "BYTE ARRAY SIZE: " + size);
byte[] item = new byte[size];
ois.read(item);
received.add(item);
}
Message message = handler.obtainMessage(BITMAP,
received);
Log.d("CONSEQUENCES", "READ IMAGES");
Log.d("CONSEQUENCES", "images size = " + received.size());
handler.sendMessage(message);
}
和客户端日志:
有什么想法为什么我会收到这么大的整数或者为什么会失败吗?
最佳答案
我得到这些整数是因为整个字节数组没有被发送过来。我替换:
ois.read(item);
与
int readBytes = -1;
while (readBytes != size) {
readBytes = readBytes + ois.read(item,readBytes,size-readBytes);
}
关于java - 如何在Android上通过蓝牙发送字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353646/