netty4.1.32 pipeline的添加顺序和执行顺序

本文只想讨论一下pipeline的执行顺序问题,因为这个搞不明白就不知道先添加编码还是解码,是不是可以混淆添加等等一系列事情

1         pipeline.addLast(new outboundsHandler1()); //out1
2         pipeline.addLast(new outboundsHandler2()); //out2
3         
4         pipeline.addLast(new InboundsHandler1()); //in1
5         pipeline.addLast(new InboundsHandler2()); //in2
6         pipeline.addLast("handler", new HelloServerHandler());//in3

先说最基本的, 读入数据,需要解码数据,执行顺序和注册顺序一致 in1 --> in2 -->in3 他们之间通过 ctx.fireChannelRead(msg);进行传递

解码完成,逻辑处理,进行数据发送 通过 ctx.writeAndFlush()就完成从in -->out的转换

out的执行顺是和注册顺序相反的,也就是out2 -->out1这么个顺序 out间的传递通过ctx.writeAndFlush();函数进行传递 

ctx.channel().writeAndFlush()  和 ctx.writeAndFlush() 区别

网上说注册 outhandler的时候,必须放到最后一个inhandler前面(本例就是in3前面),其实是不准确的 比如

1         pipeline.addLast(new InboundsHandler1()); //in1
2         pipeline.addLast(new InboundsHandler2()); //in2
3         pipeline.addLast("handler", new HelloServerHandler());//in3
4 
5         pipeline.addLast(new outboundsHandler1()); //out1
6         pipeline.addLast(new outboundsHandler2()); //out2

比如我注册时out放后面,接收执行到in3时,执行ctx.writeAndFlush(),会发生什么呢,outhandler不调用,因为ctx.writeAndFlush()是从当前节点往前查找out类handler,而out节点注册在当前节点后边

这种情况要想让他执行outhandler的处理,应该执行ctx.channel().writeAndFlush();这是从链表结尾开始往前查找out类handler,这就是两种writeAndFlush的区别

网上这种说法是使用ctx.writeAndFlush()的一种使用方式而已,还是要根据情况深入理解!

out就是继承自ChannelOutboundHandlerAdapter的 通常可以用来编码

in就是继承自ChannelInboundHandlerAdapter的,通常用来解码

猜你喜欢

转载自www.cnblogs.com/ruber/p/10186571.html