示例代码
// 必须先添加解码器/编码器 保证数据流动的顺序正确
ch.pipeline().addLast("decoder",
new ProtobufDecoder(BalanceNetProtocol.BasePackage.getDefaultInstance()));
ch.pipeline().addLast("encoder",
new ProtobufEncoder());
ch.pipeline().addLast(new IdleStateHandler(10, 10, 10));
ch.pipeline().addLast(defaultEventExecutorGroup, new SessionHandler(controllerServer));
在pipeline上添加解码/编码器,用来做字节到消息的转化。注意编码器在pipeline添加的位置
Netty中的通用基类的解码器ByteToMessageDecoder,是一个ChannelInboundHandler。read事件传播的时候开始读取数据解码。只有完整解析出消息才会接着往下传播read事件。
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 其只关心ByteBuf的消息的解码
if (msg instanceof ByteBuf) {
// 存放解码出来的结果的容器
CodecOutputList out = CodecOutputList.newInstance();
try {
ByteBuf data = (ByteBuf) msg;
// cumulation变量是一个可以累加ByteBuf的ByteBuf
first = cumulation == null;
// 如果是第一次解码
if (first) {
// cumulation直接赋值
cumulation = data;
} else {
// 如果是第n次,将data加入cumulation
// 此时cumulation中有没解码完的旧数据和到来的新数据
cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);
}
// 子类实现具体的解码逻辑
callDecode(ctx, cumulation, out);
}
// ...
finally {
// cumulation中的数据若被读完,需要被释放
if (cumulation != null && !cumulation.isReadable()) {
numReads = 0;
cumulation.release();
cumulation = null;
} else if (++ numReads >= discardAfterReads) {
// We did enough reads already try to discard some bytes so we not risk to see a OOME.
// See https://github.com/netty/netty/issues/4275
numReads = 0;
discardSomeReadBytes();
}
int size = out.size();
decodeWasNull = !out.insertSinceRecycled();
// 将out中的数据往下传播给下一个Handler
// 此时out存放的是解码之后的结果
// 若out长度size为空,则不会传播
// 只有完整解析出消息才会接着往下传播read事件
fireChannelRead(ctx, out, size);
out.recycle();
}
} else {
// 不关心,往下传播即可
ctx.fireChannelRead(msg);
}
}
这里最为关键的是callDecode方法,其做了一些操作判断,然后调用了子类的解码逻辑
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
try {
// 不断循环,直到无数据可读
// 当然,也会有一些条件主动break循环
while (in.isReadable()) {
// 先判断未解码之前,结果集合的长度
int outSize = out.size();
// 结果集合里有东西,先把结果给传播出去
if (outSize > 0) {
fireChannelRead(ctx, out, outSize);
// 清空结果列表
out.clear();
if (ctx.isRemoved()) {
break;
}
// reset outSize值
outSize = 0;
}
// 记录没解码之前读的位置,以便后续统计读了多少数据出去
int oldInputLength = in.readableBytes();
// 调用子类decode
decodeRemovalReentryProtection(ctx, in, out);
if (ctx.isRemoved()) {
break;
}
// 如果旧的结果列表的长度和现在的长度一样
// 证明没有解码到东西,证明了现在的消息还不够可以解码出一个数据
if (outSize == out.size()) {
// 如果ByteBuf也没被读过,证明为半包数据(不完整)
if (oldInputLength == in.readableBytes()) {
break;
} else {
// 如果到了这里,证明ByteBuf读了一些数据出去,但结果并没有增加
// 这说明了刚刚只是丢弃了一些不读的数据,再解码一次
continue;
}
}
// 代码到这里还是没读过,是异常的现象
if (oldInputLength == in.readableBytes()) {
throw new DecoderException(
StringUtil.simpleClassName(getClass()) +
".decode() did not read anything but decoded a message.");
}
if (isSingleDecode()) {
break;
}
}
} catch (DecoderException e) {
throw e;
} catch (Exception cause) {
throw new DecoderException(cause);
}
}
- 有消息(字节)进来,被ByteToMessageDecoder接收到,判断若为字节则处理,其会在成员变量中保存一个ByteBuf存放字节的数据结构,此数据结构可累加
- 循环处理字节数据,以下两种情况跳出循环
- 读完了数据
- 子类没解码出东西(结果列表没有变化)
- 若结果列表中有元素,则将结果元素一个个往下传播read事件,这里结果列表的一个元素视为一个完整的数据包。这样,在解码器后面的Handler就可以很方便的直接操作某个具体的对象即可,不需要关心数据是否是完整的一个数据包和从字节中解析数据的过程。没有解析出就不传播。
765




被折叠的 条评论
为什么被折叠?



