前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty之添加Handler

Netty之添加Handler

作者头像
书唐瑞
发布2022-06-02 13:51:30
3140
发布2022-06-02 13:51:30
举报
文章被收录于专栏:Netty历险记

在使用Netty开发过程,业务上的处理需要使用添加的Handler进行处理. 此篇我们以服务端为例.

此篇文章也不是详细介绍Handler,只是聊聊关于添加Handler的一些细节.

代码语言:javascript
复制
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,而是通过如下方式

代码语言:javascript
复制
.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也是需要这样的类似操作

代码语言:javascript
复制
.childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());

    }
})
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Netty历险记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档