码迷,mamicode.com
首页 > Web开发 > 详细

netty tcp拆包

时间:2017-08-03 10:00:58      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:ant   equals   length   red   arraylist   return   normal   tostring   als   

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;
    }

 

netty tcp拆包

标签:ant   equals   length   red   arraylist   return   normal   tostring   als   

原文地址:http://www.cnblogs.com/winkey4986/p/7263384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!