在上面的一篇文章中,有说明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(ChannelHandlerContext ctx) throws Exception {
OutputMessageBuf out = OutputMessageBuf.get();
try {
ByteBuf in = ctx.inboundByteBuffer();
if (in.isReadable()) {
callDecode(ctx, in);
}
decodeLast(ctx, in, out);
} catch (CodecException e) {
throw e;
} catch (Throwable cause) {
throw new DecoderException(cause);
} finally {
if (out.drainToNextInbound(ctx)) {
ctx.fireInboundBufferUpdated();
}
ctx.fireChannelInactive();
}
}
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in) {
boolean wasNull = false;
OutputMessageBuf out = OutputMessageBuf.get();
try {
while (in.isReadable()) { //是否有数据可以读
int outSize = out.size(); //当前存放经过转码的数据的buffer
int oldInputLength = in.readableBytes(); //可以读的数据量
decode(ctx, in, out); //调用用户定义的decode方法,用来解析数据,并将解析出来的对象放到out里面
if (outSize == out.size()) { //这个表明没有解析出任何对象
wasNull = true;
if (oldInputLength == in.readableBytes()) {
break; //表示没有从in里面读取任何数据
} else {
continue;
}
}
wasNull = false;
if (oldInputLength == in.readableBytes()) {
throw new IllegalStateException(
"decode() did not read anything but decoded a message.");
}
if (isSingleDecode()) {
break;
}
}
} catch (CodecException e) {
throw e;
} catch (Throwable cause) {
throw new DecoderException(cause);
} finally {
if (out.drainToNextInbound(ctx)) { //把数据写到接下来的inboundhandler的inboundbuffer里面去
decodeWasNull = false;
ctx.fireInboundBufferUpdated(); //激活下一个handler的inboundBufferUpdated方法,用于处理刚刚写进去的数据
} else {
if (wasNull) {
decodeWasNull = true;
}
}
}
}
/**
* Decode the from one {@link ByteBuf} to an other. This method will be called till either the input
* {@link ByteBuf} has nothing to read anymore, till nothing was read from the input {@link ByteBuf} or till
* this method returns {@code null}.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link ByteToByteDecoder} belongs to
* @param in the {@link ByteBuf} from which to read data
* @param out the {@link MessageBuf} to which decoded messages should be added
* @throws Exception is thrown if an error accour
*/
//用户自己定义的decode方法,用于将读取的byte类型的数据转化为用户自定义的类型
protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, MessageBuf<Object> out) throws Exception;
/**
* Is called one last time when the {@link ChannelHandlerContext} goes in-active. Which means the
* {@link #channelInactive(ChannelHandlerContext)} was triggered.
*
* By default this will just call {@link #decode(ChannelHandlerContext, ByteBuf, MessageBuf)} but sub-classes may
* override this for some special cleanup operation.
*/
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, MessageBuf<Object> out) throws Exception {
decode(ctx, in, out);
}
}
这里需要注意到重写的方法是inboundBufferUpdated,也就是当数据进来的时候会调用的方法,又直接调用callDecode方法来处理,而callDecode方法的实现也还算是比较的简单,上面的注释也都基本上说的比较的清楚了,无非是调用用户定义的decode方法,用于将读进来的byte数据转化为用户自己定义的数据类型,然后再将转化的结果放入到一个messagebuf里面。。。
这里可以看到decode方法是个抽象的方法,所以需要用户自己继承ByteToMessageDecoder类型,然后重写decode方法用于按照自己的规则将数据转化为自定义的类型。。。
另外比较重要的是finally部分的代码:
if (out.drainToNextInbound(ctx)) { //把数据写到接下来的inboundhandler的inboundbuffer里面去
decodeWasNull = false;
ctx.fireInboundBufferUpdated(); //激活下一个handler的inboundBufferUpdated方法,用于处理刚刚写进去的数据
} else {
if (wasNull) {
decodeWasNull = true;
}
}
其实这部分看名字也都能知道这些方法的意思吧,猜都能猜出来:见当前messagebuf里面的数据写到下一个inboundhandler的buffer里面去。。。然后再激活下一个inboundhandler的inboundBufferUpdated方法,用于处理数据。。我们还是来看看drainToNextInbound方法的定义吧:
public boolean drainToNextInbound(ChannelHandlerContext ctx) {
final int size = size(); //当前buf存放的数据的量
if (size == 0) {
return false;
}
//有可能是bytebuf的类型
final int byteBufCnt = this.byteBufCnt;
if (byteBufCnt == 0 || ctx.nextInboundBufferType() != BufType.BYTE) {
return drainTo(ctx.nextInboundMessageBuffer()) > 0;
}
final ByteBuf nextByteBuf = ctx.nextInboundByteBuffer();
if (byteBufCnt == size) {
// Contains only ByteBufs
for (Object o = poll();;) {
writeAndRelease(nextByteBuf, (ByteBuf) o);
if ((o = poll()) == null) {
break;
}
}
} else {
// Contains both ByteBufs and non-ByteBufs (0 < byteBufCnt < size())
final MessageBuf<Object> nextMsgBuf = ctx.nextInboundMessageBuffer(); //获取下一个inboundhandler的messagebuffer
for (Object o = poll();;) { //将当前buffer里面存放的message放入到下一个handler的buffer里面去
if (o instanceof ByteBuf) {
writeAndRelease(nextByteBuf, (ByteBuf) o);
} else {
nextMsgBuf.add(o);
}
if ((o = poll()) == null) {
break;
}
}
}
return true;
}
代码还是比较的简单,无非是将数据当前buf里面的数据取出来,然后放到下一个handler的buf里面去就行了,这里需要注意的是,这里有可能也是byte类型的。。。
这样,decode出来的数据,就转移到了下一个inboundhandler的buffer里面了,那么下一个handler就可以处理这些数据了。。。
这里我们再稍微来看看ChannelInboundMessageHandlerAdapter这个类型吧,它的inboundBufferUpdated方法定义如下:
@Override
public final void inboundBufferUpdated(ChannelHandlerContext ctx) throws Exception {
ChannelHandlerUtil.handleInboundBufferUpdated(ctx, this);
}
很简单,我们再来看看它的具体实现吧: public static <T> void handleInboundBufferUpdated(
ChannelHandlerContext ctx, SingleInboundMessageHandler<T> handler) throws Exception {
MessageBuf<Object> in = ctx.inboundMessageBuffer();
if (in.isEmpty() || !handler.beginMessageReceived(ctx)) {
return;
}
MessageBuf<Object> out = ctx.nextInboundMessageBuffer();
int oldOutSize = out.size();
try {
//这里一个循环可以看出,对于每一个解码出来的object对象,都会调用用户定义的messageReceived方法来处理
for (;;) {
Object msg = in.poll();
if (msg == null) {
break;
}
if (!handler.acceptInboundMessage(msg)) { //如果当前这个handler不支持这个类型,那么将数据写到下一个handler的buffer里面
out.add(msg);
continue;
}
@SuppressWarnings("unchecked")
T imsg = (T) msg;
try {
handler.messageReceived(ctx, imsg); //调用用户定义的messageReceived方法来处理message
} finally {
BufUtil.release(imsg);
}
}
} catch (Signal abort) {
abort.expect(ABORT);
} finally {
if (oldOutSize != out.size()) { //这里表示由message写入到下一个inboundhandler的inbuffer里面,那么需要进行处理
ctx.fireInboundBufferUpdated(); //这里会激活下一个inboundhandler的inboundBufferUpdated方法,用于处理写进去的message
}
handler.endMessageReceived(ctx);
}
}
意思也很简单吧,将buf里面的数据一个一个的取出来,然后调用用户自己定义的messageReceived方法用于处理这些数据。。
好了,decoder就差不多了,下一篇看一下encoder吧。。。