【Netty 】Netty 知识整理 (1) fireChannelRead用法
发布日期:2021-05-08 10:59:50 浏览次数:23 分类:精选文章

本文共 953 字,大约阅读时间需要 3 分钟。

概述

fireChannelRead表示传递消息至下一个处理器,因为pipline的原因,我们可能有一个链式的处理队列,这个队列有头和尾之分,那么消息通常从头处理器进入。

假设现有队列A、B、C,一条消息消息首先进入A,如果A不显示调用fireChannelRead将消息传递至B的话,那么B和C永远收不到消息。

我们来看个例子:

public class AHandler extends ChannelInboundHandlerAdapter {    public void channelRead(ChannelHandlerContext ctx, Object msg) throws  Exception {      ctx.fireChannelRead(msg);

上面的例子表示A处理器把msg透传给了B,当然了,A不一定直接透传,也可以传递处理过的消息。我们来看个例子:

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {           ByteBuf buf = (ByteBuf) msg;        byte[] bytes = new byte[buf.readableBytes()];        // 读取输入的消息至byte数组        buf.readBytes(bytes);        int length = bytes.length + 1;        ByteBuf newBuf = ctx.alloc().buffer(length);        newBuf.writeBytes(bytes);        // 多写入一个boolean类型的数据        newBuf.writeBoolean(false);        ReferenceCountUtil.release(msg);        ctx.fireChannelRead(newBuf);    }

这个例子是在原有的消息之上,封装了一个boolean类型的数据,然后再传递至下一个处理器。

注意:原有的消息需要释放。

上一篇:eclipse引用sun.misc开头的类
下一篇:【UML】免费的UML绘图工具yEd

发表评论

最新留言

不错!
[***.144.177.141]2025年04月10日 11时38分35秒