ChannelPipeline为ChannelHandler链提供了容器,并且定义了该链上的入站和出站事件。当initChannel()被调用时,ChannelInitializer将在ChannelPipeline中安装一组自定义的ChannelHandler。他们的执行顺序就是添加顺序。
Server
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
public static void main(String[] args) {
//创建一个独立的EventLoopGroup
DefaultEventLoopGroup group = new DefaultEventLoopGroup();
new ServerBootstrap()
.group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast("h1",new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("h1");
super.channelRead(ctx,msg);
}
}).addLast("h2",new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("h2");
super.channelRead(ctx,msg);
}
}).addLast("h3",new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("h3");
super.channelRead(ctx,msg);
ch.writeAndFlush(ctx.alloc().buffer().writeBytes("server".getBytes()));
}
}).addLast("h4",new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
logger.info("h4");
super.write(ctx, msg, promise);
}
}).addLast("h5",new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
logger.info("h5");
super.write(ctx, msg, promise);
}
}).addLast("h6",new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
logger.info("h6");
super.write(ctx, msg, promise);
}
});
}
})
.bind(8080);
}
}
控制台
注意入站和出站的顺序!