java netty之ByteToMessageDecoder

在上面的一篇文章中,有说明ByteToMessageDecoder是怎么使用的,那么这一篇就来讲讲它是怎么实现的。。

首先还是来看一下它的继承体系:


它直接继承自ChannelInboundByteHandlerAdapter类型,至于说这个类型的介绍,在前面的文章中就已经有了说明,无非是实现了那些inboundhandler的方法,不过实现的都非常的粗糙,另外一些handler可以直接继承它,重写其中自己感兴趣的方法就可以了。。。

好吧,接下来我们来看看ByteToMessageDecoder的定义吧:

[java]  view plain copy
  1. public abstract class ByteToMessageDecoder  
  2.     extends ChannelInboundByteHandlerAdapter {  
  3.   
  4.     private volatile boolean singleDecode;  
  5.     private boolean decodeWasNull;  
  6.   
  7.     /** 
  8.      * If set then only one message is decoded on each {@link #inboundBufferUpdated(ChannelHandlerContext)} call. 
  9.      * This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. 
  10.      * 
  11.      * Default is {@code false} as this has performance impacts. 
  12.      */  
  13.     public void setSingleDecode(boolean singleDecode) {  
  14.         this.singleDecode = singleDecode;  
  15.     }  
  16.   
  17.     /** 
  18.      * If {@code true} then only one message is decoded on each 
  19.      * {@link #inboundBufferUpdated(ChannelHandlerContext)} call. 
  20.      * 
  21.      * Default is {@code false} as this has performance impacts. 
  22.      */  
  23.     public boolean isSingleDecode() {  
  24.         return singleDecode;  
  25.     }  
  26.   
  27.     @Override  
  28.     public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {  
  29.         callDecode(ctx, in);   //当有数据进来的时候,直接调用callDecode方法  
  30.     }  
  31.   
  32.     @Override  
  33.     public void channelReadSuspended(ChannelHandlerContext ctx) throws Exception {  
  34.         if (decodeWasNull) {  
  35.             decodeWasNull = false;  
  36.             if (!ctx.channel().config().isAutoRead()) {  
  37.                 ctx.read();  
  38.             }  
  39.         }  
  40.         super.channelReadSuspended(ctx);  
  41.     }  
  42.   
  43.     @Override  
  44.     public void channelInactive(ChannelHandlerContext ctx) throws Exception {  
  45.         OutputMessageBuf out = OutputMessageBuf.get();  
  46.         try {  
  47.             ByteBuf in = ctx.inboundByteBuffer();  
  48.             if (in.isReadable()) {  
  49.                 callDecode(ctx, in);  
  50.             }  
  51.             decodeLast(ctx, in, out);  
  52.         } catch (CodecException e) {  
  53.             throw e;  
  54.         } catch (Throwable cause) {  
  55.             throw new DecoderException(cause);  
  56.         } finally {  
  57.             if (out.drainToNextInbound(ctx)) {  
  58.                 ctx.fireInboundBufferUpdated();  
  59.             }  
  60.             ctx.fireChannelInactive();  
  61.         }  
  62.     }  
  63.   
  64.     protected void callDecode(ChannelHandlerContext ctx, ByteBuf in) {  
  65.         boolean wasNull = false;  
  66.         OutputMessageBuf out = OutputMessageBuf.get();  
  67.         try {  
  68.             while (in.isReadable()) {  //是否有数据可以读  
  69.                 int outSize = out.size();   //当前存放经过转码的数据的buffer  
  70.                 int oldInputLength = in.readableBytes(); //可以读的数据量  
  71.                 decode(ctx, in, out);   //调用用户定义的decode方法,用来解析数据,并将解析出来的对象放到out里面  
  72.                 if (outSize == out.size()) {   //这个表明没有解析出任何对象  
  73.                     wasNull = true;  
  74.                     if (oldInputLength == in.readableBytes()) {  
  75.                         break;   //表示没有从in里面读取任何数据  
  76.                     } else {  
  77.                         continue;  
  78.                     }  
  79.                 }  
  80.   
  81.                 wasNull = false;  
  82.                 if (oldInputLength == in.readableBytes()) {  
  83.                     throw new IllegalStateException(  
  84.                          "decode() did not read anything but decoded a message.");  
  85.                 }  
  86.   
  87.                 if (isSingleDecode()) {  
  88.                     break;  
  89.                 }  
  90.             }  
  91.         } catch (CodecException e) {  
  92.             throw e;  
  93.         } catch (Throwable cause) {  
  94.             throw new DecoderException(cause);  
  95.         } finally {  
  96.             if (out.drainToNextInbound(ctx)) {  //把数据写到接下来的inboundhandler的inboundbuffer里面去  
  97.                 decodeWasNull = false;  
  98.                 ctx.fireInboundBufferUpdated();  //激活下一个handler的inboundBufferUpdated方法,用于处理刚刚写进去的数据  
  99.             } else {  
  100.                 if (wasNull) {  
  101.                     decodeWasNull = true;  
  102.                 }  
  103.             }  
  104.         }  
  105.     }  
  106.   
  107.     /** 
  108.      * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input 
  109.      * {@link ByteBuf} has nothing to read anymore, till nothing was read from the input {@link ByteBuf} or till 
  110.      * this method returns {@code null}. 
  111.      * 
  112.      * @param ctx           the {@link ChannelHandlerContext} which this {@link ByteToByteDecoder} belongs to 
  113.      * @param in            the {@link ByteBuf} from which to read data 
  114.      * @param out           the {@link MessageBuf} to which decoded messages should be added 
  115.  
  116.      * @throws Exception    is thrown if an error accour 
  117.      */  
  118.    //用户自己定义的decode方法,用于将读取的byte类型的数据转化为用户自定义的类型  
  119.     protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, MessageBuf<Object> out) throws Exception;  
  120.   
  121.     /** 
  122.      * Is called one last time when the {@link ChannelHandlerContext} goes in-active. Which means the 
  123.      * {@link #channelInactive(ChannelHandlerContext)} was triggered. 
  124.      * 
  125.      * By default this will just call {@link #decode(ChannelHandlerContext, ByteBuf, MessageBuf)} but sub-classes may 
  126.      * override this for some special cleanup operation. 
  127.      */  
  128.     protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, MessageBuf<Object> out) throws Exception {  
  129.         decode(ctx, in, out);  
  130.     }  
  131. }  

这里需要注意到重写的方法是inboundBufferUpdated,也就是当数据进来的时候会调用的方法,又直接调用callDecode方法来处理,而callDecode方法的实现也还算是比较的简单,上面的注释也都基本上说的比较的清楚了,无非是调用用户定义的decode方法,用于将读进来的byte数据转化为用户自己定义的数据类型,然后再将转化的结果放入到一个messagebuf里面。。。

这里可以看到decode方法是个抽象的方法,所以需要用户自己继承ByteToMessageDecoder类型,然后重写decode方法用于按照自己的规则将数据转化为自定义的类型。。。

另外比较重要的是finally部分的代码:

[java]  view plain copy
  1. if (out.drainToNextInbound(ctx)) {  //把数据写到接下来的inboundhandler的inboundbuffer里面去  
  2.                 decodeWasNull = false;  
  3.                 ctx.fireInboundBufferUpdated();  //激活下一个handler的inboundBufferUpdated方法,用于处理刚刚写进去的数据  
  4.             } else {  
  5.                 if (wasNull) {  
  6.                     decodeWasNull = true;  
  7.                 }  
  8.             }  

其实这部分看名字也都能知道这些方法的意思吧,猜都能猜出来:见当前messagebuf里面的数据写到下一个inboundhandler的buffer里面去。。。然后再激活下一个inboundhandler的inboundBufferUpdated方法,用于处理数据。。我们还是来看看drainToNextInbound方法的定义吧:

[java]  view plain copy
  1. public boolean drainToNextInbound(ChannelHandlerContext ctx) {  
  2.     final int size = size();   //当前buf存放的数据的量  
  3.     if (size == 0) {  
  4.         return false;  
  5.     }  
  6.     //有可能是bytebuf的类型  
  7.     final int byteBufCnt = this.byteBufCnt;  
  8.     if (byteBufCnt == 0 || ctx.nextInboundBufferType() != BufType.BYTE) {  
  9.         return drainTo(ctx.nextInboundMessageBuffer()) > 0;  
  10.     }  
  11.   
  12.     final ByteBuf nextByteBuf = ctx.nextInboundByteBuffer();  
  13.     if (byteBufCnt == size) {  
  14.         // Contains only ByteBufs  
  15.         for (Object o = poll();;) {  
  16.             writeAndRelease(nextByteBuf, (ByteBuf) o);  
  17.             if ((o = poll()) == null) {  
  18.                 break;  
  19.             }  
  20.         }  
  21.     } else {  
  22.         // Contains both ByteBufs and non-ByteBufs (0 < byteBufCnt < size())  
  23.         final MessageBuf<Object> nextMsgBuf = ctx.nextInboundMessageBuffer();   //获取下一个inboundhandler的messagebuffer  
  24.         for (Object o = poll();;) {   //将当前buffer里面存放的message放入到下一个handler的buffer里面去  
  25.             if (o instanceof ByteBuf) {  
  26.                 writeAndRelease(nextByteBuf, (ByteBuf) o);  
  27.             } else {  
  28.                 nextMsgBuf.add(o);  
  29.             }  
  30.   
  31.             if ((o = poll()) == null) {  
  32.                 break;  
  33.             }  
  34.         }  
  35.     }  
  36.   
  37.     return true;  
  38. }  

代码还是比较的简单,无非是将数据当前buf里面的数据取出来,然后放到下一个handler的buf里面去就行了,这里需要注意的是,这里有可能也是byte类型的。。。

这样,decode出来的数据,就转移到了下一个inboundhandler的buffer里面了,那么下一个handler就可以处理这些数据了。。。

这里我们再稍微来看看ChannelInboundMessageHandlerAdapter这个类型吧,它的inboundBufferUpdated方法定义如下:

[java]  view plain copy
  1. @Override  
  2. public final void inboundBufferUpdated(ChannelHandlerContext ctx) throws Exception {  
  3.     ChannelHandlerUtil.handleInboundBufferUpdated(ctx, this);  
  4. }  
很简单,我们再来看看它的具体实现吧:
[java]  view plain copy
  1. public static <T> void handleInboundBufferUpdated(  
  2.         ChannelHandlerContext ctx, SingleInboundMessageHandler<T> handler) throws Exception {  
  3.     MessageBuf<Object> in = ctx.inboundMessageBuffer();  
  4.     if (in.isEmpty() || !handler.beginMessageReceived(ctx)) {  
  5.         return;  
  6.     }  
  7.   
  8.     MessageBuf<Object> out = ctx.nextInboundMessageBuffer();  
  9.     int oldOutSize = out.size();  
  10.     try {  
  11.         //这里一个循环可以看出,对于每一个解码出来的object对象,都会调用用户定义的messageReceived方法来处理  
  12.         for (;;) {  
  13.             Object msg = in.poll();  
  14.             if (msg == null) {  
  15.                 break;  
  16.             }  
  17.   
  18.             if (!handler.acceptInboundMessage(msg)) {  //如果当前这个handler不支持这个类型,那么将数据写到下一个handler的buffer里面  
  19.                 out.add(msg);  
  20.                 continue;  
  21.             }  
  22.   
  23.             @SuppressWarnings("unchecked")  
  24.             T imsg = (T) msg;  
  25.             try {  
  26.                 handler.messageReceived(ctx, imsg);   //调用用户定义的messageReceived方法来处理message  
  27.             } finally {  
  28.                 BufUtil.release(imsg);  
  29.             }  
  30.         }  
  31.     } catch (Signal abort) {  
  32.         abort.expect(ABORT);  
  33.     } finally {  
  34.         if (oldOutSize != out.size()) {  //这里表示由message写入到下一个inboundhandler的inbuffer里面,那么需要进行处理  
  35.             ctx.fireInboundBufferUpdated();  //这里会激活下一个inboundhandler的inboundBufferUpdated方法,用于处理写进去的message  
  36.         }  
  37.   
  38.         handler.endMessageReceived(ctx);  
  39.     }  
  40. }  

意思也很简单吧,将buf里面的数据一个一个的取出来,然后调用用户自己定义的messageReceived方法用于处理这些数据。。


好了,decoder就差不多了,下一篇看一下encoder吧。。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值