我想实现的效果是,第一次接收4个字节,然后判断是否为包头,如果是包头就进行下一步,但是在限制字节,byte[] tmpHead = new byte[4]还有判断包头的时候总出错。初学者,基础不扎实,请大佬赐教。
DataInputStream is =new DataInputStream(socket.getInputStream());//实例化
byte[] tmpHead = new byte[4];//接收包头
is.read(tmpHead);//将拿到的值给tmpHead
if(is.read(tmpHead) != 0){
toastMsg("收到了");
}else {
toastMsg("没有");
}
if ((tmpHead[0] == 0x7E) && (tmpHead[1] == 0x81) && (tmpHead[2] == 0x18) && (tmpHead[3] == 0xE7)) {//判断包头
toastMsg("头验证");
byte[] tmpRest = new byte[44];//接收后续数据
is.read(tmpRest);//将拿到的值给tmpRest
byte[] Head = new byte[tmpHead.length + tmpRest.length];//拼接完整包头
System.arraycopy(tmpHead, 0, Head, 0, tmpHead.length);//合并数组
System.arraycopy(tmpRest, 0, Head, tmpHead.length, tmpRest.length);//合并数组
struct.InfoHead mInfoHead = new struct.InfoHead();//JavaStruct 对象实例化
JavaStruct.unpack(mInfoHead, Head);//unpack解包
byte[] Data = new byte[mInfoHead.dataLen];//拿到Struct包中datalen,获取下段字节长度
is.read(Data);//将拿到的值给Data
byte[] Tail = new byte[8];//包尾长度8字节
is.read(Tail);//将获取的数据给Tail
struct.Tail mTail = new struct.Tail();//实例化Tail
JavaStruct.unpack(mTail, Tail);//解包
if (mTail.packTail == 0x8F9009F8) {//判断包尾是否正确
System.out.print(mInfoHead.packHead);
System.out.print(mTail.packTail);
}
} else {
toastMsg("数据错误");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();