`
xiaoZ5919
  • 浏览: 400443 次
  • 性别: Icon_minigender_1
  • 来自: 安平人@北京
博客专栏
Group-logo
Netty学习笔记
浏览量:72762
社区版块
存档分类
最新评论

Netty笔记:FrameDecoder

 
阅读更多

     FrameDecoder是Netty Protocol Decode最关键的Decoder,几乎所有和协议解码相关的Decoder都继承自它,那到底解决了什么问题?为什么需要这样的一个部件呢?TCP的传输是基于流的,每个数据包都有可能被分片和然后重组,这时候我们就需要协议去界定一个数据包,通常来说用来方式来确定数据包的边界,一个是基于长度,简单一点就是规定数据包的长度,例如规定每个数据包的长度为100byte,FixedlengthFrameDecoder就是这样,可实际中我们的数据包并不都是固定长度,可以说是大小不一的情况更常见。怎么样解决这个问题呢?我们加一个长度属性的header,标示我们实际内容的大小,这就是LengthFieldBasedFrameDecoder。

    回归正题,为什么需要FrameDecoder,来考虑两个极端的问题:
    1. 假设我们一帧(数据包)的大小为100byte,然而socket的sendBuffer的大小只有50byte,server端的readbuffer的大小也是50byte。这就意味着我们读两次才能读完成一帧。
    2.Netty的NioWorker(Poller)是有读写控制,每次只能读到制定大小的buffer,例如一帧的大小还是100byte,Poller读到1024k,然后触发message receive事件去处理,这样第11帧只能读到24byte,显然不是一完整的帧剩余的76byte需要在下一次poll中接收。
     通过这两个问题我们发现,有时候为了读完整的一帧需要累积读多次,就像以上两种情况需要两次,我们不能读到数据就进行处理,我们得需要一个累积器,把分散的buffer累积到累积器中,再进行解码,这样就能避免一帧跨两个buffer。
     还是看看代码吧
  if (cumulation == null) {
            // the cumulation buffer is not created yet so just pass the input to callDecode(...) method 第一次的时候,累积器还没有创建,这时先解码,然后把剩余的部分加到累积器中。如果每次input都变完整的解码成一帧,没有/剩余则不会创建累积器
            callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
   //如果有剩余放入累积
            if (input.readable()) {
                // seems like there is something readable left in the input buffer. So create the cumulation buffer and copy the input into it
                (this.cumulation = newCumulationBuffer(ctx, input.readableBytes())).writeBytes(input);
            }
        } else {
            assert cumulation.readable();
            boolean fit = false;
            
            int readable = input.readableBytes();
            int writable = cumulation.writableBytes();
            int w = writable - readable;
            if (w < 0) {
                int readerIndex = cumulation.readerIndex();
                if (w + readerIndex >= 0) {
                    // the input will fit if we discard all read bytes, so do it
                    cumulation.discardReadBytes();
                    fit = true;
                }
 
0
0
分享到:
评论
1 楼 scriptguy 2013-01-11  
跟mina中的累加解码器道理一样,呵呵

相关推荐

Global site tag (gtag.js) - Google Analytics