在使用Netty开发过程,业务上的处理需要使用添加的Handler进行处理. 此篇我们以服务端为例.
此篇文章也不是详细介绍Handler,只是聊聊关于添加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();
以上代码基本属于开发服务端的标准代码. 但是上面的代码我故意写错一个地方,那就是调用了2次handler方法.handler方法是向服务端的Channel对应的Pipeline中添加Handler处理器.2次调用的话,后者会覆盖前者,即BusinessInHandler2会覆盖BusinessInHandler1.
我们的本意是想向Pipeline中添加2个Handler,但是并不是通过调用2次handler,而是通过如下方式
.handler(new ChannelInitializer<ServerSocketChannel>() {
@Override
protected void initChannel(ServerSocketChannel ch) throws Exception {
ch.pipeline().addLast(new BusinessInHandler1());
ch.pipeline().addLast(new BusinessInHandler2());
}
})
通过ChannelInitializer,重写initChannel方法,才能达到向Pipeline中添加多个Handler的效果.
不仅是服务端的Channel,客户端的Channel也是需要这样的类似操作
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
}
})