当前位置: 首页 > news >正文

netty 学习 (2)Handler的执行顺序

摘要 Handler在netty中,无疑占据着非常重要的地位。Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。 参考自:http://blog.csdn.net/u013252773/article/details/21195593

Handler在netty中,无疑占据着非常重要的地位。Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。

Netty中的所有handler都实现自ChannelHandler接口。按照输出输出来分,分为ChannelInboundHandler、ChannelOutboundHandler两大类。ChannelInboundHandler对从客户端发往服务器的报文进行处理,一般用来执行解码、读取客户端数据、进行业务处理等;ChannelOutboundHandler对从服务器发往客户端的报文进行处理,一般用来进行编码、发送报文到客户端。

Netty中,可以注册多个handler。ChannelInboundHandler按照注册的先后顺序执行;ChannelOutboundHandler按照注册的先后顺序逆序执行,如下图所示,按照注册的先后顺序对Handler进行排序,request进入Netty后的执行顺序为:

下面例子涉及的类包括:

一、HelloServer:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

packagecom.yao.nettyhandler;

importio.netty.bootstrap.ServerBootstrap;

importio.netty.channel.ChannelFuture;

importio.netty.channel.ChannelInitializer;

importio.netty.channel.ChannelOption;

importio.netty.channel.EventLoopGroup;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

importio.netty.channel.socket.nio.NioServerSocketChannel;

publicclass HelloServer {

    publicvoid start(intport) throwsException {

        EventLoopGroup bossGroup = newNioEventLoopGroup();

        EventLoopGroup workerGroup = newNioEventLoopGroup();

        try{

            ServerBootstrap b = newServerBootstrap();

            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)

                    .childHandler(newChannelInitializer<SocketChannel>() {

                                @Override

                                publicvoid initChannel(SocketChannel ch) throwsException {

                                    // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1

                                    ch.pipeline().addLast(newOutboundHandler1());

                                    ch.pipeline().addLast(newOutboundHandler2());

                                    // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2

                                    ch.pipeline().addLast(newInboundHandler1());

                                    ch.pipeline().addLast(newInboundHandler2());

                                }

                            }).option(ChannelOption.SO_BACKLOG,128)

                    .childOption(ChannelOption.SO_KEEPALIVE,true);

            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();

        }finally{

            workerGroup.shutdownGracefully();

            bossGroup.shutdownGracefully();

        }

    }

    publicstatic void main(String[] args) throwsException {

        HelloServer server = newHelloServer();

        server.start(8000);

    }

}

二、InboundHandler1:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

packagecom.yao.nettyhandler;

importio.netty.channel.ChannelHandlerContext;

importio.netty.channel.ChannelInboundHandlerAdapter;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

publicclass InboundHandler1 extendsChannelInboundHandlerAdapter {

    privatestatic Log logger = LogFactory.getLog(InboundHandler1.class);

    @Override

    publicvoid channelRead(ChannelHandlerContext ctx, Object msg) throwsException {

        logger.info("InboundHandler1.channelRead: ctx :" + ctx);

         

        // 通知执行下一个InboundHandler

        //ctx.fireChannelRead(msg);

    }

    @Override

    publicvoid channelReadComplete(ChannelHandlerContext ctx) throwsException {

        logger.info("InboundHandler1.channelReadComplete");

        ctx.flush();

    }

}

三、InboundHandler2:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

packagecom.yao.nettyhandler;

importio.netty.buffer.ByteBuf;

importio.netty.channel.ChannelHandlerContext;

importio.netty.channel.ChannelInboundHandlerAdapter;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

publicclass InboundHandler2 extendsChannelInboundHandlerAdapter {

    privatestatic Log  logger  = LogFactory.getLog(InboundHandler2.class);

    @Override

    // 读取Client发送的信息,并打印出来

    publicvoid channelRead(ChannelHandlerContext ctx, Object msg) throwsException {

        logger.info("InboundHandler2.channelRead: ctx :" + ctx);

        ByteBuf result = (ByteBuf) msg;

        byte[] result1 = newbyte[result.readableBytes()];

        result.readBytes(result1);

        String resultStr = newString(result1);

        System.out.println("Client said:" + resultStr);

        result.release();

        ctx.write(msg);

    }

    @Override

    publicvoid channelReadComplete(ChannelHandlerContext ctx) throwsException {

        logger.info("InboundHandler2.channelReadComplete");

        ctx.flush();

    }

}

四、OutboundHandler1 : 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

packagecom.yao.nettyhandler;

importio.netty.buffer.ByteBuf;

importio.netty.channel.ChannelHandlerContext;

importio.netty.channel.ChannelOutboundHandlerAdapter;

importio.netty.channel.ChannelPromise;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

publicclass OutboundHandler1 extendsChannelOutboundHandlerAdapter {

    privatestatic Log  logger  = LogFactory.getLog(OutboundHandler1.class);

    @Override

    // 向client发送消息

    publicvoid write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throwsException {

        logger.info("OutboundHandler1.write");

        String response = "I am ok!";

        ByteBuf encoded = ctx.alloc().buffer(4* response.length());

        encoded.writeBytes(response.getBytes());

        ctx.write(encoded);

        ctx.flush();

    }

     

     

}

五、OutboundHandler2:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

packagecom.yao.nettyhandler;

importio.netty.channel.ChannelHandlerContext;

importio.netty.channel.ChannelOutboundHandlerAdapter;

importio.netty.channel.ChannelPromise;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

publicclass OutboundHandler2 extendsChannelOutboundHandlerAdapter {

    privatestatic Log  logger  = LogFactory.getLog(OutboundHandler2.class);

     

    @Override

    publicvoid write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throwsException {

        logger.info("OutboundHandler2.write");

        // 执行下一个OutboundHandler

        super.write(ctx, msg, promise);

    }

}

下面是客户端

六、HelloClient:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

packagecom.yao.nettyhandler;

importio.netty.bootstrap.Bootstrap;

importio.netty.channel.ChannelFuture;

importio.netty.channel.ChannelInitializer;

importio.netty.channel.ChannelOption;

importio.netty.channel.EventLoopGroup;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

importio.netty.channel.socket.nio.NioSocketChannel;

publicclass HelloClient {

    publicvoid connect(String host, intport) throwsException {

        EventLoopGroup workerGroup = newNioEventLoopGroup();

        try{

            Bootstrap b = newBootstrap();

            b.group(workerGroup);

            b.channel(NioSocketChannel.class);

            b.option(ChannelOption.SO_KEEPALIVE,true);

            b.handler(newChannelInitializer<SocketChannel>() {

                @Override

                publicvoid initChannel(SocketChannel ch) throwsException {

                    ch.pipeline().addLast(newHelloClientIntHandler());

                }

            });

            // Start the client.

            ChannelFuture f = b.connect(host, port).sync();

            f.channel().closeFuture().sync();

        }finally{

            workerGroup.shutdownGracefully();

        }

    }

    publicstatic void main(String[] args) throwsException {

        HelloClient client = newHelloClient();

        client.connect("127.0.0.1",8000);

    }

}

七、HelloClientIntHandler:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

packagecom.yao.nettyhandler;

importio.netty.buffer.ByteBuf;

importio.netty.channel.ChannelHandlerContext;

importio.netty.channel.ChannelInboundHandlerAdapter;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

publicclass HelloClientIntHandler extendsChannelInboundHandlerAdapter {

    privatestatic Log  logger  = LogFactory.getLog(HelloClientIntHandler.class);

    @Override

    // 读取服务端的信息

    publicvoid channelRead(ChannelHandlerContext ctx, Object msg) throwsException {

        logger.info("HelloClientIntHandler.channelRead");

        ByteBuf result = (ByteBuf) msg;

        byte[] result1 = newbyte[result.readableBytes()];

        result.readBytes(result1);

        result.release();

        ctx.close();

        System.out.println("Server said:" + newString(result1));

    }

    @Override

    // 当连接建立的时候向服务端发送消息 ,channelActive 事件当连接建立的时候会触发

    publicvoid channelActive(ChannelHandlerContext ctx) throwsException {

        logger.info("HelloClientIntHandler.channelActive");

        String msg = "Are you ok?";

        ByteBuf encoded = ctx.alloc().buffer(4* msg.length());

        encoded.writeBytes(msg.getBytes());

        ctx.write(encoded);

        ctx.flush();

    }

}

八、总结:

在使用Handler的过程中,需要注意:
1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
4、Handler的消费处理放在最后一个处理。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • netty 学习 (1)
  • Java设计模式——工厂设计模式
  • Java开发中的23种设计模式详解(转)
  • CMMI学习
  • NetConf协议说明
  • HashMap 与 ConcurrentHashMap
  • java-策略模式
  • SNMP4J简介
  • SNMP 使用SNMP4J V2进行TRAP
  • JTable的清空小技巧以及JTable的详细介绍
  • JFrame简单的例子
  • org.apache.catalina.deploy.WebXml addFilter
  • Tomcat version 6.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 Web modules
  • myEclipse中的web项目直接引入到eclipse中运行
  • 常用的网络传输协议
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • python3.6+scrapy+mysql 爬虫实战
  • 2017年终总结、随想
  • 77. Combinations
  • dva中组件的懒加载
  • JAVA并发编程--1.基础概念
  • Redis在Web项目中的应用与实践
  • vue-loader 源码解析系列之 selector
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • 从 Android Sample ApiDemos 中学习 android.animation API 的用法
  • 和 || 运算
  • 计算机常识 - 收藏集 - 掘金
  • 世界上最简单的无等待算法(getAndIncrement)
  • 算法---两个栈实现一个队列
  • 微信小程序--------语音识别(前端自己也能玩)
  • ​HTTP与HTTPS:网络通信的安全卫士
  • ​探讨元宇宙和VR虚拟现实之间的区别​
  • # Spring Cloud Alibaba Nacos_配置中心与服务发现(四)
  • #VERDI# 关于如何查看FSM状态机的方法
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (1)(1.13) SiK无线电高级配置(六)
  • (1)无线电失控保护(二)
  • (20050108)又读《平凡的世界》
  • (C++哈希表01)
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (二)c52学习之旅-简单了解单片机
  • (二十三)Flask之高频面试点
  • (附源码)spring boot基于Java的电影院售票与管理系统毕业设计 011449
  • (附源码)ssm失物招领系统 毕业设计 182317
  • (四)activit5.23.0修复跟踪高亮显示BUG
  • (循环依赖问题)学习spring的第九天
  • (一)使用Mybatis实现在student数据库中插入一个学生信息
  • (自用)交互协议设计——protobuf序列化
  • ***检测工具之RKHunter AIDE
  • .gitignore
  • .net core MVC 通过 Filters 过滤器拦截请求及响应内容
  • .net framework 4.0中如何 输出 form 的name属性。
  • .net FrameWork简介,数组,枚举
  • .NET MVC第三章、三种传值方式
  • .NET_WebForm_layui控件使用及与webform联合使用