我试图使用蓝牙将图像从一个设备发送到另一设备,为此我使用了Android蓝牙聊天应用程序源代码,并且在发送String时工作正常,但是如果我将图像作为字节数组发送,则while循环不会中断或EOF不会从Inputstream读取时达到。
型号:1
它正确接收图像。但是这里我需要传递resultByteArray length。但是我不知道长度。如何知道inputstream中字节数组的长度?inputstream.available()返回0。
while(true)
{
byte[] resultByteArray = new byte[150827];
DataInputStream dataInputStream = new DataInputStream(mmInStream);
dataInputStream.readFully(resultByteArray);
mHandler.obtainMessage(AppConstants.MESSAGE_READ, dataInputStream.available(),-1, resultByteArray).sendToTarget();
}
型号:2
在这段代码中,循环不中断,
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] resultByteArray = new byte[1024];
int bytesRead;
while ((bytesRead = mmInStream.read(resultByteArray)) != -1) {
Log.i("BTTest1", "bytesRead=>"+bytesRead);
bao.write(resultByteArray,0,bytesRead);
}
final byte[] data = bao.toByteArray();
也尝试过,byte[] resultByteArray = IOUtils.toByteArray(mmInStream);
但也没有用。我关注了蓝牙聊天示例。
如何解决这个问题?
如评论中所述,服务器需要将图像长度放在实际图像数据的前面。图像长度信息的长度应固定为4个字节。
然后在while循环中,您需要先获取4个字节来确定图像的长度。之后,从输入流中读取确切长度的字节。那是实际的图像。
在连接处于活动状态时,while循环不需要中断。实际上,它需要在同一while循环中等待另一个图像数据。的InputStream.read()
是一个阻断功能和线程将被睡眠,直到它从输入流中接收到足够的数据。
然后,您可以在紧接前一个图像数据之后再等待4个字节,作为另一个图像的开始。
while(true) {
try {
// Get the length first
byte[] bytesLengthOfImage = new byte[4];
mmInStream.read(bytesLengthOfImage);
int lengthOfImage = 0;
{
ByteBuffer buffer = ByteBuffer.wrap(bytesLengthOfImage);
buffer.order(ByteOrder.BIG_ENDIAN); // Assume it is network byte order.
lengthOfImage = buffer.getInt();
}
byte[] actualImage = new byte[lengthOfImage]; // Mind the memory allocation.
mmInStream.read(actualImage);
mHandler.obtainMessage(AppConstants.MESSAGE_READ, lengthOfImage,-1, actualImage).sendToTarget();
} catch (Exception e) {
if(e instanceof IOException) {
// If the connection is closed, break the loop.
break;
}
else {
// Handle errors
break;
}
}
}
这是一种简化的通信协议。有一个易于协议实现的开源框架,称为NFCommunicator。
https://github.com/Neofect/NFCommunicator
对于一个简单的项目而言,这可能是过分规范的,但值得一看。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句