netty tcp拆包

private List<byte[]> getCompletePacket(byte[] bytes, ByteBuf byteBuf) {
        byte[] clone = bytes.clone();
        int i = 0;
        List<byte[]> ret = Lists.newArrayList();
        while (i + YTLConstant.HEADER_LENGTH < clone.length) {
            byte[] header = Arrays.copyOfRange(clone, i, YTLConstant.HEADER_LENGTH);
            if (Arrays.equals(header, YTLConstant.ELECTRICITY_METER_RECEIVE_HEADER)
                    || Arrays.equals(header, YTLConstant.RELAY_SETTING_RECEIVE_NORMAL_HEADER)
                    || Arrays.equals(header, YTLConstant.RELAY_SETTING_RECEIVE_WRONG_HEADER)
                    || Arrays.equals(header, YTLConstant.RELAY_STATUS_RECEIVE_HEADER)) {
                //读取电表 接收数据 头
                if (YTLConstant.HEADER_LENGTH + 1 < clone.length) {//加1为了判断长度位
                    byte infoLength = clone[YTLConstant.HEADER_LENGTH];
                    int tailIndex = YTLConstant.HEADER_LENGTH + infoLength + 2;//CRC长度为2
                    if (tailIndex <= clone.length - 1 && bytes[tailIndex] == YTLConstant.TAIL) {
                        i = tailIndex + 1;
                        if (i == clone.length) {
                            ret.add(bytes);
                            byteBuf.skipBytes(i);
                        } else {
                            ret.add(Arrays.copyOf(clone, i));//从clone中截取长度为i的数组
                            clone = Arrays.copyOfRange(clone, i, clone.length - 1);
                            byteBuf.skipBytes(i);
                            i = 0;
                        }
                    }else{
                        //无效指令跳过
                        byteBuf.skipBytes(clone.length);
                        break;
                    }
                }
            }else{
                //无效指令跳过
                if (logger.isDebugEnabled()) {
                    logger.debug("Received an unregistered cmd,the header is : "+Arrays.toString(header));
                }
                byteBuf.skipBytes(clone.length);
                break;
            }
        }
        return ret;
    }
原文地址:https://www.cnblogs.com/winkey4986/p/7263384.html