Netty學(xué)習(xí)筆記五-LengthFieldBasedFrameDecoder源碼分析

上一節(jié)中提到了對象反序列化解析器ObjectDecoder,ObjectDecoder是繼承自LengthFieldBasedFrameDecoder构捡,LengthFieldBasedFrameDecoder是Netty通用的拆包器

LengthFieldBasedFrameDecoder用法

LengthFieldBasedFrameDecoder源碼解釋中是這么說的:
通過長度域lengthFieldLength對ByteBuf進行動態(tài)拆分的decoder,特別適合當(dāng)有一個int做了消息包體頭部進行反序列化
LengthFieldBasedFrameDecoder有很多配置參數(shù)所以可以對任何指定長度域lengthFieldLength的消息進行反序列化她我,所以經(jīng)常用戶客戶端和服務(wù)端的通信協(xié)議。
LengthFieldBasedFrameDecoder的幾個重要參數(shù):
lengthFiledLength: 長度域大小
maxFrameLength:最大幀長度迫横,即單個包最大的長度
lengthFieldOffset:表示數(shù)據(jù)長度字段開始的偏移量
lengthAdjustment:長度調(diào)整值
initialBytesToStrip:表示從整個包第一個字節(jié)開始鸦难,向后忽略的字節(jié)數(shù)
1、基于長度的拆包


image.png

長度域2個字節(jié)员淫,偏移量0合蔽,initialBytesToStrip為0
2、過濾包頭Header介返,只獲取包體數(shù)據(jù)


image.png

lengthFieldLength = 2 //數(shù)據(jù)長度為2個字節(jié)
initialBytesToStrip=2 //等于數(shù)據(jù)的長度拴事,意思就是跳過數(shù)據(jù)長度字節(jié)
lengthFieldOffset=0 //偏移量為0
3沃斤、lengthFieldLength代表數(shù)據(jù)Header+Body的長度,
image.png

4刃宵、基于可調(diào)整長度的拆包
image.png

總之衡瓶,反序列首先會跳過initialBytesToStrip個字節(jié)讀取buyBuf,lengthAdjustment表示長度域后還有多少個字節(jié)才是真正的數(shù)據(jù)長度。lengthFieldOffset表示還有多少偏移才是真正的長度域

源碼分析

構(gòu)造函數(shù)

 public LengthFieldBasedFrameDecoder(
            ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
            int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        if (byteOrder == null) {
            throw new NullPointerException("byteOrder");
        }

        if (maxFrameLength <= 0) {
            throw new IllegalArgumentException(
                    "maxFrameLength must be a positive integer: " +
                    maxFrameLength);
        }

        if (lengthFieldOffset < 0) {
            throw new IllegalArgumentException(
                    "lengthFieldOffset must be a non-negative integer: " +
                    lengthFieldOffset);
        }

        if (initialBytesToStrip < 0) {
            throw new IllegalArgumentException(
                    "initialBytesToStrip must be a non-negative integer: " +
                    initialBytesToStrip);
        }

        if (lengthFieldOffset > maxFrameLength - lengthFieldLength) {
            throw new IllegalArgumentException(
                    "maxFrameLength (" + maxFrameLength + ") " +
                    "must be equal to or greater than " +
                    "lengthFieldOffset (" + lengthFieldOffset + ") + " +
                    "lengthFieldLength (" + lengthFieldLength + ").");
        }

        this.byteOrder = byteOrder;
        this.maxFrameLength = maxFrameLength;
        this.lengthFieldOffset = lengthFieldOffset;
        this.lengthFieldLength = lengthFieldLength;
        this.lengthAdjustment = lengthAdjustment;
        lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength;
        this.initialBytesToStrip = initialBytesToStrip;
        this.failFast = failFast;
    }

lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength;表示長度域后第一個字節(jié)在整個包的偏移量
具體的拆包協(xié)議:

@Override
    protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    }
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
      //是否丟棄超出長度的數(shù)據(jù)幀 默認為false
        if (discardingTooLongFrame) {
            long bytesToDiscard = this.bytesToDiscard;
            int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
            in.skipBytes(localBytesToDiscard);
            bytesToDiscard -= localBytesToDiscard;
            this.bytesToDiscard = bytesToDiscard;

            failIfNecessary(false);
        }
      //如果buf中可讀字節(jié)數(shù)小于長度域最小偏移量 說明肯定讀不到長度域 直接返回
        if (in.readableBytes() < lengthFieldEndOffset) {
            return null;
        }
    //bytebuf讀位置索引+長度域偏移量=長度域在整個buf中實際偏移量
        int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    //獲取實際未調(diào)整的包長度
        long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);
      //如果包長度小于0 拋異常
        if (frameLength < 0) {
            in.skipBytes(lengthFieldEndOffset);
            throw new CorruptedFrameException(
                    "negative pre-adjustment length field: " + frameLength);
        }
      //整個包的長度 = 未調(diào)整的包長度+長度域調(diào)整值+長度域偏移量
        frameLength += lengthAdjustment + lengthFieldEndOffset;
      //如果整個包長度小于長度域偏移量 異常
        if (frameLength < lengthFieldEndOffset) {
            in.skipBytes(lengthFieldEndOffset);
            throw new CorruptedFrameException(
                    "Adjusted frame length (" + frameLength + ") is less " +
                    "than lengthFieldEndOffset: " + lengthFieldEndOffset);
        }
    //整個包長度大于最大定義的數(shù)據(jù)包長度 丟棄模式
        if (frameLength > maxFrameLength) {
            //多余的字節(jié)數(shù) = 數(shù)據(jù)包長度-buf可讀字節(jié)數(shù)
            long discard = frameLength - in.readableBytes();
            tooLongFrameLength = frameLength;
          // 多余的字節(jié)數(shù)小于0牲证,表示當(dāng)前可讀字節(jié)已達到frameLength哮针,直接跳過frameLength個字節(jié),丟棄之后坦袍,后面有可能就是一個合法的數(shù)據(jù)包
            if (discard < 0) {
                // buffer contains more bytes then the frameLength so we can discard all now
                in.skipBytes((int) frameLength);
            } else {
                // Enter the discard mode and discard everything received so far.
                discardingTooLongFrame = true;
               // 當(dāng)前可讀字節(jié)未達到frameLength十厢,說明后面未讀到的字節(jié)也需要丟棄,進入丟棄模式捂齐,先把當(dāng)前累積的字節(jié)全部丟棄
                bytesToDiscard = discard;
                in.skipBytes(in.readableBytes());
            }
            failIfNecessary(true);
            return null;
        }

        // never overflows because it's less than maxFrameLength
        int frameLengthInt = (int) frameLength;
        if (in.readableBytes() < frameLengthInt) {
            return null;
        }
      //如果需要跳過的字節(jié)數(shù)大于數(shù)據(jù)包長度 直接拋異常
        if (initialBytesToStrip > frameLengthInt) {
            in.skipBytes(frameLengthInt);
            throw new CorruptedFrameException(
                    "Adjusted frame length (" + frameLength + ") is less " +
                    "than initialBytesToStrip: " + initialBytesToStrip);
        }
    //跳過字節(jié)數(shù)
        in.skipBytes(initialBytesToStrip);

        // extract frame
      //拿到當(dāng)前buf的讀偏移量
        int readerIndex = in.readerIndex();
      //實際數(shù)據(jù)包長度 = 整個包長度減去忽略的字節(jié)數(shù)
        int actualFrameLength = frameLengthInt - initialBytesToStrip;
    //拿到待抽取的數(shù)據(jù)幀
        ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
      //移動讀指針
        in.readerIndex(readerIndex + actualFrameLength);
        return frame;
    }

getUnadjustedFrameLength獲取未調(diào)整數(shù)據(jù)長度的源碼:


protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
//入?yún)ffsset是in.readerIndex() + lengthFieldOffset蛮放,即buf讀指針+長度偏移量,
//那么獲取長度字段所在的位置奠宜,然后讀取消息長度字段所占字節(jié)數(shù)的字節(jié)(消息長度字段占用的字節(jié)數(shù)是協(xié)議約定好的)
//讀取出來的數(shù)值就是消息長度的值了包颁。
       buf = buf.order(order);
       long frameLength;
       switch (length) {
       case 1:
           frameLength = buf.getUnsignedByte(offset);
           break;
       case 2:
           frameLength = buf.getUnsignedShort(offset);
           break;
       case 3:
           frameLength = buf.getUnsignedMedium(offset);
           break;
       case 4:
           frameLength = buf.getUnsignedInt(offset);
           break;
       case 8:
           frameLength = buf.getLong(offset);
           break;
       default:
           throw new DecoderException(
                   "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
       }
       return frameLength;
   }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市压真,隨后出現(xiàn)的幾起案子娩嚼,更是在濱河造成了極大的恐慌,老刑警劉巖滴肿,帶你破解...
    沈念sama閱讀 212,383評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件岳悟,死亡現(xiàn)場離奇詭異,居然都是意外死亡嘴高,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評論 3 385
  • 文/潘曉璐 我一進店門和屎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拴驮,“玉大人,你說我怎么就攤上這事柴信√灼。” “怎么了?”我有些...
    開封第一講書人閱讀 157,852評論 0 348
  • 文/不壞的土叔 我叫張陵随常,是天一觀的道長潜沦。 經(jīng)常有香客問我,道長绪氛,這世上最難降的妖魔是什么唆鸡? 我笑而不...
    開封第一講書人閱讀 56,621評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮枣察,結(jié)果婚禮上争占,老公的妹妹穿的比我還像新娘燃逻。我一直安慰自己,他們只是感情好臂痕,可當(dāng)我...
    茶點故事閱讀 65,741評論 6 386
  • 文/花漫 我一把揭開白布伯襟。 她就那樣靜靜地躺著,像睡著了一般握童。 火紅的嫁衣襯著肌膚如雪姆怪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,929評論 1 290
  • 那天澡绩,我揣著相機與錄音稽揭,去河邊找鬼。 笑死英古,一個胖子當(dāng)著我的面吹牛淀衣,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播召调,決...
    沈念sama閱讀 39,076評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼膨桥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了唠叛?” 一聲冷哼從身側(cè)響起只嚣,我...
    開封第一講書人閱讀 37,803評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎艺沼,沒想到半個月后册舞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,265評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡障般,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,582評論 2 327
  • 正文 我和宋清朗相戀三年调鲸,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挽荡。...
    茶點故事閱讀 38,716評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡藐石,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出定拟,到底是詐尸還是另有隱情于微,我是刑警寧澤,帶...
    沈念sama閱讀 34,395評論 4 333
  • 正文 年R本政府宣布青自,位于F島的核電站株依,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏延窜。R本人自食惡果不足惜恋腕,卻給世界環(huán)境...
    茶點故事閱讀 40,039評論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逆瑞。 院中可真熱鬧吗坚,春花似錦祈远、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至牡彻,卻和暖如春扫沼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背庄吼。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評論 1 266
  • 我被黑心中介騙來泰國打工缎除, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人总寻。 一個月前我還...
    沈念sama閱讀 46,488評論 2 361
  • 正文 我出身青樓器罐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親渐行。 傳聞我的和親對象是個殘疾皇子轰坊,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,612評論 2 350

推薦閱讀更多精彩內(nèi)容

  • 拆包的原理 關(guān)于拆包原理的上一篇博文 netty源碼分析之拆包器的奧秘 中已詳細闡述,這里簡單總結(jié)下:netty的...
    簡書閃電俠閱讀 44,961評論 28 71
  • 簡介 用簡單的話來定義tcpdump祟印,就是:dump the traffic on a network肴沫,根據(jù)使用者...
    JasonShi6306421閱讀 1,234評論 0 1
  • 簡介 用簡單的話來定義tcpdump,就是:dump the traffic on a network蕴忆,根據(jù)使用者...
    保川閱讀 5,947評論 1 13
  • 午夜獨對失眠中颤芬, 星星綿羊萬遍窮, 如若非是身不適套鹅, 定邀杜康對月空站蝠! —— 藍玉堂《原創(chuàng)》本人作品全部...
    藍玉堂閱讀 333評論 1 2
  • 當(dāng)我25歲的時候菱魔,我跟自己說28歲前結(jié)婚,但轉(zhuǎn)眼就28了减牺,當(dāng)我28的時候我跟自己說30之前結(jié)婚豌习。然后上天還算...
    Tina卡閱讀 1,160評論 0 0