在上面的一篇文章中,有说明ByteToMessageDecoder是怎么使用的,那么这一篇就来讲讲它是怎么实现的。。
首先还是来看一下它的继承体系:
它直接继承自ChannelInboundByteHandlerAdapter类型,至于说这个类型的介绍,在前面的文章中就已经有了说明,无非是实现了那些inboundhandler的方法,不过实现的都非常的粗糙,另外一些handler可以直接继承它,重写其中自己感兴趣的方法就可以了。。。
好吧,接下来我们来看看ByteToMessageDecoder的定义吧:
public abstract class ByteToMessageDecoder
extends ChannelInboundByteHandlerAdapter {
private volatile boolean singleDecode;
private boolean decodeWasNull;
/**
* If set then only one message is decoded on each {@link #inboundBufferUpdated(ChannelHandlerContext)} call.
* This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up.
*
* Default is {@code false} as this has performance impacts.
*/
public void setSingleDecode(boolean singleDecode) {
this.singleDecode = singleDecode;
}
/**
* If {@code true} then only one message is decoded on each
* {@link #inboundBufferUpdated(ChannelHandlerContext)} call.
*
* Default is {@code false} as this has performance impacts.
*/
public boolean isSingleDecode() {
return singleDecode;
}
@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
callDecode(ctx, in); //当有数据进来的时候,直接调用callDecode方法
}
@Override
public void channelReadSuspended(ChannelHandlerContext ctx) throws Exception {
if (decodeWasNull) {
decodeWasNull = false;
if (!ctx.channel().config().isAutoRead()) {
ctx.read();
}
}
super.channelReadSuspended(ctx);
}
@Override
public void channelInactive(ChannelH