上一篇【第80篇】Netty学习路线图与总结——从入门到精通的完整路径下一篇【第82篇】ChannelOutboundBuffer源码深度解析——Netty写缓冲区的秘密一、Codec继承体系ByteToMessageDecoder字节→消息 ├── FixedLengthFrameDecoder ├── LengthFieldBasedFrameDecoder ├── LineBasedFrameDecoder └── DelimiterBasedFrameDecoder MessageToMessageDecoder消息→消息 └── StringDecoder, ObjectDecoder... MessageToByteEncoder消息→字节 └── LengthFieldPrepender, StringEncoder... ByteToMessageCodec组合byte↔msg二、ByteToMessageDecoder核心publicabstractclassByteToMessageDecoderextendsChannelInboundHandlerAdapter{ByteBufcumulation;// 累积缓冲区// 收到新数据publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg){ByteBufdata(ByteBuf)msg;cumulationcumulator.cumulate(ctx.alloc(),cumulation,data);callDecode(ctx,cumulation,out);}// 用户实现解码数据protectedabstractvoiddecode(ChannelHandlerContextctx,ByteBufin,ListObjectout);}三、callDecode循环解码protectedvoidcallDecode(ChannelHandlerContextctx,ByteBufin,ListObjectout){while(in.isReadable()){intoldInputLengthin.readableBytes();decode(ctx,in,out);// 调用用户decode()if(out.isEmpty()){if(oldInputLengthin.readableBytes())break;// 没消费→退出continue;// 消费了但没产出继续}// 产出消息→触发channelReadfireChannelRead(ctx,out,out.size());out.clear();}}四、cumulation两种模式// MERGE复制合并ByteBufbufferalloc.buffer(old.readableBytes()in.readableBytes());buffer.writeBytes(old).writeBytes(in);old.release();in.release();// COMPOSITE零拷贝组合CompositeByteBufcompositealloc.compositeBuffer();composite.addComponents(true,old,in);五、总结机制说明cumulation累积不完整数据callDecode循环解码直到无数据安全保护没消费没产出→防止死循环上一篇【第80篇】Netty学习路线图与总结——从入门到精通的完整路径下一篇【第82篇】ChannelOutboundBuffer源码深度解析——Netty写缓冲区的秘密