概述
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類型的數據,然后再傳遞至下一個處理器。
注意:原有的消息需要釋放。