pipeline
// out handler
socketChannel.pipeline().addLast(new StringEncoder());
// in handler
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new MyServerChannelInBoundHandler1());
socketChannel.pipeline().addLast(new MyServerChannelInBoundHandler2());
注意【MyServerChannelInBoundHandler1】必须在【MyServerChannelInBoundHandler2】的上面
【MyServerChannelInBoundHandler1.java】
@Slf4j
public class MyServerChannelInBoundHandler1 extends SimpleChannelInboundHandler<String>
{
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
log.info("MyServerChannelInBoundHandler1.channelRead0[" + ctx.channel().remoteAddress() + "]:" + msg);
String retMsg = String.format("server have received data from you:[%s]", msg.trim());
ctx.writeAndFlush(retMsg); // 发送数据出去
ctx.fireChannelRead(retMsg); // 这一句会触发下一个InBoundHandler的【channelRead】和【channelRead0】被触发
}
}
注意上面调用了【writeAndFlush(retMsg)】
注意上面调用【fireChannelRead(retMsg)】时参数是被修改过的【retMsg】,而不是【msg】。
【MyServerChannelInBoundHandler2.java】
@Slf4j
public class MyServerChannelInBoundHandler2 extends SimpleChannelInboundHandler<String>
{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("MyServerChannelInBoundHandler2.channelRead[" + ctx.channel().remoteAddress() + "]:" + msg);
super.channelRead(ctx, msg);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
log.info("MyServerChannelInBoundHandler2.channelRead0[" + ctx.channel().remoteAddress() + "]:" + msg);
ctx.writeAndFlush(msg); // 发送数据出去,这里的msg是被上面的InBoundHandler修改过的
}
}
注意【ctx.writeAndFlush()】方法被调用了两次,所以数据其实是被发送了两次出去。
在正常使用中,如果一个InBoundHandler确定了数据是要传给下一个InBoundHandler的话,本handler是不会发送数据的,而是会将数据交给下一个handler去处理,发送数据也由下一个handler发送。