当前位置:首页 > 开发 > 编程语言 > 网络编程 > 正文

Netty源码学习-ReplayingDecoder

发表于: 2013-12-13   作者:bylijinnan   来源:转载   浏览:
摘要: ReplayingDecoder是FrameDecoder的子类,不熟悉FrameDecoder的,可以先看看 http://bylijinnan.iteye.com/blog/1982618 API说,ReplayingDecoder简化了操作,比如: FrameDecoder在decode时,需要判断数据是否接收完全: public class IntegerH
ReplayingDecoder是FrameDecoder的子类,不熟悉FrameDecoder的,可以先看看
http://bylijinnan.iteye.com/blog/1982618

API说,ReplayingDecoder简化了操作,比如:

FrameDecoder在decode时,需要判断数据是否接收完全:

public class IntegerHeaderFrameDecoder extends FrameDecoder {

   protected Object decode(ChannelHandlerContext ctx,
                           Channel channel,
                           ChannelBuffer buf) throws Exception {

     if (buf.readableBytes() < 4) {
        return null;
     }

     buf.markReaderIndex();
     int length = buf.readInt();

     if (buf.readableBytes() < length) {
        buf.resetReaderIndex();
        return null;
     }

     return buf.readBytes(length);
   }
 }




而ReplayingDecoder则隐藏了这些判断,好像数据已经接收完全了一样:


 public class IntegerHeaderFrameDecoder
      extends ReplayingDecoder<VoidEnum> {

   protected Object decode(ChannelHandlerContext ctx,
                           Channel channel,
                           ChannelBuffer buf,
                           VoidEnum state) throws Exception {
	 int length = buf.readInt();
     return buf.readBytes(length);
   }
 }


可见,ReplayingDecoder使用起来要简单、直观

除此之外,
很多时候frame的结构不会是“length + content”这么简单,如果结构复杂了,
FrameDecoder的if语句就会非常多,且先到达的sub-frame就会被多次decode
ReplayingDecoder允许用户自定义state,表示decode到哪一部分了,从而下
一次数据到达时,直接从nextState开始decode

那ReplayingDecoder这是怎么做到“好像数据已经接收完全了一样”?
事实上它跟FrameDecoder的思路是一样的,只是它在数据接收不完全时,
“悄悄地失败”。这主要是通过ReplayingDecoderBuffer来实现的:

 class ReplayingDecoderBuffer implements ChannelBuffer {

    private static final Error REPLAY = new ReplayError();

    private final ReplayingDecoder<?> parent;
    private boolean terminated;

	//ReplayingDecoder作为参数
    ReplayingDecoderBuffer(ReplayingDecoder<?> parent) {
        this.parent = parent;
    }

	/*ReplayingDecoderBuffer实际上是FrameDecoder里面的cumulation(类型为ChannelBuffer)
	FrameDecoder里面,对数据的累积接收,以及数据的读取,都是在cumulation,
	而ReplayingDecoderBuffer对cumulation进行了封装,在数据不完全时,读取操作都会抛出Error
	*/
    private ChannelBuffer buf() {
        return parent.internalBuffer();
    }
	
	public byte getByte(int index) {
        checkIndex(index);
        return buf().getByte(index);
    }
	
	//数据接收不完全时,抛出Error,在ReplayingDecoder里捕获
	private void checkIndex(int index) {
        if (index > buf().writerIndex()) {
            throw REPLAY;
        }
    }
 
 
 


 public abstract class ReplayingDecoder<T extends Enum<T>>
        extends FrameDecoder {

	//创建了ReplayingDecoderBuffer
    private final ReplayingDecoderBuffer replayable = new ReplayingDecoderBuffer(this);
    private T state;	
	
	//标记着下一次数据读取的开始位置,也代表着已经decode到哪一部分了
    private int checkpoint;
	
	protected void checkpoint() {
        ChannelBuffer cumulation = this.cumulation;
        if (cumulation != null) {
            checkpoint = cumulation.readerIndex();
        } else {
            checkpoint = -1; // buffer not available (already cleaned up)
        }
    }
	
    protected void checkpoint(T state) {
        checkpoint();
        setState(state);
    }

	protected T setState(T newState) {
        T oldState = state;
        state = newState;
        return oldState;
    }
	
	//这个方法交由子类实现,子类可以定义更详细、语义更丰富的state
	 protected abstract Object decode(ChannelHandlerContext ctx,
            Channel channel, ChannelBuffer buffer, T state) throws Exception;
			
	//重点在这个方法,注意对ReplayError的处理
	private void callDecode(
            ChannelHandlerContext context, Channel channel,
            ChannelBuffer input, ChannelBuffer replayableInput, SocketAddress remoteAddress) throws Exception {
        while (input.readable()) {
            int oldReaderIndex = checkpoint = input.readerIndex();
            Object result = null;
            T oldState = state;
            try {
			
				//如果数据接收还不完全,decode方法就会抛出ReplayError
				//因为decode方法会调用replayableInput(类型为ReplayingDecoderBuffer)的getXXX方法
                result = decode(context, channel, replayableInput, state);
                if (result == null) {
					//省略
                }
            } catch (ReplayError replay) {
			
				//数据不充足,回退到checkpoint,下一次messageReceived再试
                // Return to the checkpoint (or oldPosition) and retry.
                int checkpoint = this.checkpoint;
                if (checkpoint >= 0) {
                    input.readerIndex(checkpoint);
                } else {
                    // Called by cleanup() - no need to maintain the readerIndex
                    // anymore because the buffer has been released already.
                }
            }

            if (result == null) {
                // Seems like more data is required.
                // Let us wait for the next notification.
                break;
            }

            // A successful decode
            unfoldAndFireMessageReceived(context, remoteAddress, result);
        }
    }
	
 


ReplayingDecoder的使用,API给出了一个简单的例子:
 
  public class IntegerHeaderFrameDecoder
      extends ReplayingDecoder<MyDecoderState> {

   private int length;

   public IntegerHeaderFrameDecoder() {
     // Set the initial state.
     super(MyDecoderState.READ_LENGTH);
   }

   protected Object decode(ChannelHandlerContext ctx,
                           Channel channel,
                           ChannelBuffer buf,
                           MyDecoderState state) throws Exception {
     switch (state) {
     case READ_LENGTH:
       length = buf.readInt();
	   
	   //设置下一次的decode从哪一个state开始
       checkpoint(MyDecoderState.READ_CONTENT);
     case READ_CONTENT:
       ChannelBuffer frame = buf.readBytes(length);
       checkpoint(MyDecoderState.READ_LENGTH);
       return frame;
     default:
       throw new Error("Shouldn't reach here.");
     }
   }
 }
 
 


注意到上面的switch语句是不需要break的,因为case READ_LENGTH后:
1.如果数据不充足,那就会在buf.readBytes(length)里面抛出ReplayError,相当于有了break语句
2.如果数据充足,那就接着decode,最终成功并 return frame

除了API以外,下面这两篇文章写得非常好:
http://biasedbit.com/netty-tutorial-replaying-decoder/
http://biasedbit.com/an-enhanced-version-of-replayingdecoder-for-netty/

其中第二个例子,文章中给的代码不是很完整,我补全并做了一个简单的测试:
https://github.com/bylijinnan/nettyLearn/tree/master/ljn-netty3-learn/src/main/java/com/ljn/handler/replay





Netty源码学习-ReplayingDecoder

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
背景 最忌工作中接触到Netty相关应用场景,之前看过mima的部分源码,所以最近看了Netty的部分源码和
类结构图: 不了解Executor接口原理的可以查看concurrent包中的api介绍,这里只介绍Netty中EventExe
Transport API的核心: Channel接口 类图表示Channel含有Pipeline和Config接口,pipeline上一节有所
Netty是一个基于JAVA NIO类库的异步通信框架,它的架构特点是:异步非阻塞、基于事件驱动、高性能、
先看下netty的channel对象关联关系。channel是由channelfactory来创建的,channelfactory又分为clie
感谢网友【黄亿华】投递本稿。 上一篇文章我们概要介绍了Netty的原理及结构,下面几篇文章我们开始
上一篇文章我们概要介绍了Netty的原理及结构,下面几篇文章我们开始对Netty的各个模块进行比较详细
netty里面最重要的应该是ChannelHandler,这个里面也是用户编程直接打交道的接口,也是串行于Channe
本文采用版本为Jboss Netty-3.2.4.Final,Jboss Netty示例example、几十页的user guide是快速学习的
本文为原创,转载请注明出处 netty 4源码分析-write Netty的写操作由两个步骤组成: Write:将msg存
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号