使用Netty开发服务端的时候,需要向服务端Channel(NioServerSocketChannel)和客户端Channel(NioSocketChannel)添加Handler,大致如下
NioEventLoopGroup boss = new NioEventLoopGroup(1); NioEventLoopGroup worker = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class) .handler(new BusinessInHandler1()) .handler(new BusinessInHandler2()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); } }); serverBootstrap.bind("127.0.0.1", 8086).sync();通过调用handler()可以给服务端Channel添加Handler。但是这样的话, 后者会覆盖前者,BusinessInHandler2会覆盖BusinessInHandler1,因此也达不到 向服务端Channel添加多个Handler的目的,有且只能使用ChannelInitializer才能做到。
.handler(new ChannelInitializer<ServerSocketChannel>() { @Override protected void initChannel(ServerSocketChannel ch) throws Exception { ch.pipeline().addLast(new BusinessInHandler1()); ch.pipeline().addLast(new BusinessInHandler2()); } })