1.SimpleChannelInboundHandler
SimpleChannelInboundHandler 实现了channelRead 方法,使用了模版模式,最后有一个释放资源的动作。
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean release = true; try { if (acceptInboundMessage(msg)) { @SuppressWarnings("unchecked") I imsg = (I) msg; channelRead0(ctx, imsg); } else { release = false; ctx.fireChannelRead(msg); } } finally { if (autoRelease && release) { ReferenceCountUtil.release(msg); } } }
当继承SimpleChannelInboundHandler时 需要的实现的方法是channelRead0。
2.发消息的两种方式
channelHandlerContext.write(msg);这种方式消息将从ChannelPipeline中下一个ChannelHandler开始流动。
private void write(Object msg, boolean flush, ChannelPromise promise) { AbstractChannelHandlerContext next = findContextOutbound(); final Object m = pipeline.touch(msg, next); EventExecutor executor = next.executor(); if (executor.inEventLoop()) { if (flush) { next.invokeWriteAndFlush(m, promise); } else { next.invokeWrite(m, promise); } } else { AbstractWriteTask task; if (flush) { task = WriteAndFlushTask.newInstance(next, m, promise); } else { task = WriteTask.newInstance(next, m, promise); } safeExecute(executor, task, promise, m); } }
直接写入channel中,导致消息直接从ChannelPipeline的尾端开始流动
channelHandlerContext.channel().write(in);
@Override public final ChannelFuture write(Object msg) { return tail.write(msg); }