ChannelHandlerContext
ChannelHandlerContext代表了一个ChannelHandler和ChannelPipeline之间的关系,ChannelHandlerContext创建于ChannelHandler被载入到ChannelPipeline的时候,ChannelHandlerContext主要功能是管理在同一ChannelPipeline中各个ChannelHandler的交互
ChannelHandlerContext,Channel,ChannelPipeline提供的一些方法,下图时三者者之间的关系
ByteToMessageDecoder
一个抽象类需要我们自己重写decode方法
class ByteToIntegerDecoder extends ByteToMessageDecoder{@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {while(in.readableBytes() > 4){out.add(in.readInt());}}}
ctx是decode属于的ChannelHandlerContext,in是用来读取的数据,out是我们转换后的对象列表
channelRead
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) {cumulation = data;} else {cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);}callDecode(ctx, cumulation, out);} catch (DecoderException e) {throw e;} catch (Throwable t) {throw new DecoderException(t);} finally {if (cumulation != null && !cumulation.isReadable()) {cumulation.release();cumulation = null;}int size = out.size();for (int i = 0; i < size; i ++) {ctx.fireChannelRead(out.get(i));}out.recycle();}} else {ctx.fireChannelRead(msg);}}
cumulation是代表累加的byte数据,即上一次decode剩下的byte,cumulator是累加器,默认使用MERGE_CUMULATOR就是使用内存复制来进行累加。累加完之后调用callDecode(ctx, cumulation, out),callDecode中循环调用我们要实现的抽象方法decode(ctx,in,out)来解码,知道不能继续解。在finally中对out列表中的每一个对象调用ctx.fireChannelRead(out.get(i))
触发ChannelPipeline后面的ChannelHandler的channelRead事件
