摘要
ByteToMessageDecoder在Netty5处理的过程中起着很重要的作用,主要就是进行字节累积对象的管理工作
欢迎大家关注我的微博 http://weibo.com/hotbain 会将发布的开源项目技术贴通过微博通知大家,希望大家能够互勉共进!谢谢!也很希望能够得到大家对我博文的反馈,写出更高质量的文章!!
正文
源代码分析(代码注释)
ByteToMessageDecoder在Netty中起着很大的作用,用来解决半包字节累积问题。粘贴部分重要代码:
public abstract class ByteToMessageDecoder extends ChannelHandlerAdapter {
ByteBuf cumulation;
private boolean singleDecode;
private boolean first;
protected ByteToMessageDecoder() {
if (getClass().isAnnotationPresent(Sharable.class)) {
//因为每一个ByteToMessageDecoder都有针对某个socket的累积对象
//故是一个不可以共享的对象类型
throw new IllegalStateException("@Sharable annotation is not allowed");
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
RecyclableArrayList out = RecyclableArrayList.newInstance();
try {
ByteBuf data = (ByteBuf) msg;
first = cumulation == null;
if (first) {