socket使用过程中遇到个问题:因为数据量太大,大约有2w个字节的响应数据报,之前同事代码实现的时候没有做完整的接收处理。仅使用InputStream.available()做了一次读取,然后就遇到问题了!
会发现,每次读取的时候获得的长度值不固定,且均无法获得完整长度。另一方面,响应的数据报并不会告知发送的长度是多少,但是有结束标志:byte类型 03是结束标志。
所以做了重新实现:
byte[] buffer = null;
byte[] tempBuffer = new byte[0];//
try {
int count = 0;
while (true) {
count = is.available() ;// 返回03 退出
Logger.debug("count======" + count);
if (count != 0) {
buffer = new byte[count]; // 缓冲区
is.read(buffer);
tempBuffer = ByteUtils.byteMerger(tempBuffer, buffer);//拼接接收报文
LogUtils.d(TAG, "end>>byte>>" + buffer[count -1]);
if (buffer[count - 1] == 03) {//03 结束
LogUtils.d(TAG, "end while>>count>>" + count);
buffer = tempBuffer;
break;
} else {
Thread.sleep(500);
}
} else {
Thread.sleep(500);
}
}
} catch (IOException e) {
e.printStackTrace();
Logger.debug("Recive:读取流数据超时异常 =" + e.toString());
close();
return null;
} catch (Exception e) {
e.printStackTrace();
close();
return null;
}
因为是多次接收,且次数不固定,所以需要while循环接收,同时写了工具类进行byte数据的拼接:
public class ByteUtils {
private static final String TAG = "ByteUtils";
/**
* 组合两个byte数组
* @param first
* @param second
* @return
*/
public static byte[] byteMerger(byte[] first, byte[] second){
LogUtils.d(TAG, "byteMarger");
byte[] temp = new byte[first.length + second.length];
int i = 0;
for (byte b : first){
temp[i] = b;
i ++;
}
for (byte b : second){
temp[i] = b;
i ++;
}
return temp;
}
}