Netty4.0学习笔记系列之二: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后的执行顺序为:

基本的概念就说到这,下面用一个例子来进行验证。该例子模拟Client与Server间的通讯,Server端注册了2个ChannelInboundHandler、2个ChannelOutboundHandler。当Client连接到Server后,会向Server发送一条消息。Server端通过ChannelInboundHandler 对Client发送的消息进行读取,通过ChannelOutboundHandler向client发送消息。最后Client把接收到的信息打印出来。

Server端一共有5个类:HelloServer InboundHandler1 InboundHandler2 OutboundHandler1 OutboundHandler2

1、HelloServer 代码如下

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. public class HelloServer {
  11. public void start(int port) throws Exception {
  12. EventLoopGroup bossGroup = new NioEventLoopGroup();
  13. EventLoopGroup workerGroup = new NioEventLoopGroup();
  14. try {
  15. ServerBootstrap b = new ServerBootstrap();
  16. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
  17. .childHandler(new ChannelInitializer<SocketChannel>() {
  18. @Override
  19. public void initChannel(SocketChannel ch) throws Exception {
  20. // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1
  21. ch.pipeline().addLast(new OutboundHandler1());
  22. ch.pipeline().addLast(new OutboundHandler2());
  23. // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2
  24. ch.pipeline().addLast(new InboundHandler1());
  25. ch.pipeline().addLast(new InboundHandler2());
  26. }
  27. }).option(ChannelOption.SO_BACKLOG, 128)
  28. .childOption(ChannelOption.SO_KEEPALIVE, true);
  29. ChannelFuture f = b.bind(port).sync();
  30. f.channel().closeFuture().sync();
  31. } finally {
  32. workerGroup.shutdownGracefully();
  33. bossGroup.shutdownGracefully();
  34. }
  35. }
  36. public static void main(String[] args) throws Exception {
  37. HelloServer server = new HelloServer();
  38. server.start(8000);
  39. }
  40. }

2、InboundHandler1

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.ChannelInboundHandlerAdapter;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. public class InboundHandler1 extends ChannelInboundHandlerAdapter {
  7. private static Logger   logger  = LoggerFactory.getLogger(InboundHandler1.class);
  8. @Override
  9. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  10. logger.info("InboundHandler1.channelRead: ctx :" + ctx);
  11. // 通知执行下一个InboundHandler
  12. ctx.fireChannelRead(msg);
  13. }
  14. @Override
  15. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  16. logger.info("InboundHandler1.channelReadComplete");
  17. ctx.flush();
  18. }
  19. }

3、InboundHandler2

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. public class InboundHandler2 extends ChannelInboundHandlerAdapter {
  8. private static Logger   logger  = LoggerFactory.getLogger(InboundHandler2.class);
  9. @Override
  10. // 读取Client发送的信息,并打印出来
  11. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  12. logger.info("InboundHandler2.channelRead: ctx :" + ctx);
  13. ByteBuf result = (ByteBuf) msg;
  14. byte[] result1 = new byte[result.readableBytes()];
  15. result.readBytes(result1);
  16. String resultStr = new String(result1);
  17. System.out.println("Client said:" + resultStr);
  18. result.release();
  19. ctx.write(msg);
  20. }
  21. @Override
  22. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  23. logger.info("InboundHandler2.channelReadComplete");
  24. ctx.flush();
  25. }
  26. }

4、OutboundHandler1

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelOutboundHandlerAdapter;
  5. import io.netty.channel.ChannelPromise;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
  9. private static Logger   logger  = LoggerFactory.getLogger(OutboundHandler1.class);
  10. @Override
  11. // 向client发送消息
  12. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  13. logger.info("OutboundHandler1.write");
  14. String response = "I am ok!";
  15. ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
  16. encoded.writeBytes(response.getBytes());
  17. ctx.write(encoded);
  18. ctx.flush();
  19. }
  20. }

5、OutboundHandler2

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.ChannelOutboundHandlerAdapter;
  4. import io.netty.channel.ChannelPromise;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
  8. private static Logger   logger  = LoggerFactory.getLogger(OutboundHandler2.class);
  9. @Override
  10. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  11. logger.info("OutboundHandler2.write");
  12. // 执行下一个OutboundHandler
  13. super.write(ctx, msg, promise);
  14. }
  15. }

Client端有两个类:HelloClient  HelloClientIntHandler

1、HelloClient

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioSocketChannel;
  10. public class HelloClient {
  11. public void connect(String host, int port) throws Exception {
  12. EventLoopGroup workerGroup = new NioEventLoopGroup();
  13. try {
  14. Bootstrap b = new Bootstrap();
  15. b.group(workerGroup);
  16. b.channel(NioSocketChannel.class);
  17. b.option(ChannelOption.SO_KEEPALIVE, true);
  18. b.handler(new ChannelInitializer<SocketChannel>() {
  19. @Override
  20. public void initChannel(SocketChannel ch) throws Exception {
  21. ch.pipeline().addLast(new HelloClientIntHandler());
  22. }
  23. });
  24. // Start the client.
  25. ChannelFuture f = b.connect(host, port).sync();
  26. f.channel().closeFuture().sync();
  27. } finally {
  28. workerGroup.shutdownGracefully();
  29. }
  30. }
  31. public static void main(String[] args) throws Exception {
  32. HelloClient client = new HelloClient();
  33. client.connect("127.0.0.1", 8000);
  34. }
  35. }

2、HelloClientIntHandler

[java] view plaincopy

  1. package com.guowl.testmultihandler;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
  8. private static Logger   logger  = LoggerFactory.getLogger(HelloClientIntHandler.class);
  9. @Override
  10. // 读取服务端的信息
  11. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  12. logger.info("HelloClientIntHandler.channelRead");
  13. ByteBuf result = (ByteBuf) msg;
  14. byte[] result1 = new byte[result.readableBytes()];
  15. result.readBytes(result1);
  16. result.release();
  17. ctx.close();
  18. System.out.println("Server said:" + new String(result1));
  19. }
  20. @Override
  21. // 当连接建立的时候向服务端发送消息 ,channelActive 事件当连接建立的时候会触发
  22. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  23. logger.info("HelloClientIntHandler.channelActive");
  24. String msg = "Are you ok?";
  25. ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
  26. encoded.writeBytes(msg.getBytes());
  27. ctx.write(encoded);
  28. ctx.flush();
  29. }
  30. }

server端执行结果为:

在使用Handler的过程中,需要注意:

1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。

2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。

3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。

时间: 2024-08-11 03:26:55

Netty4.0学习笔记系列之二:Handler的执行顺序(转)的相关文章

Netty4.0学习笔记系列之三:构建简单的http服务(转)

http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.Client向Server发送http请求. 2.Server端对http请求进行解析. 3.Server端向client发送http响应. 4.Client对http响应进行解析. 在该实例中,会涉及到http请求的编码.解码,http响应的编码.解码,幸运的是,Netty已经为我们提供了这些工具,

Netty4.0学习笔记系列之六:多种通讯协议支持

上文介绍了如何应用Netty开发自定义通讯协议,本文在此基础上进一步深化,研究如何同时支持不同的通讯协议. 此处所谓的通讯协议,指的是把Netty通讯管道中的二进制流转换为对象.把对象转换成二进制流的过程.转换过程追根究底还是ChannelInboundHandler.ChannelOutboundHandler的实现类在进行处理.ChannelInboundHandler负责把二进制流转换为对象,ChannelOutboundHandler负责把对象转换为二进制流. 接下来要构建一个Serve

WebService学习笔记系列(二)

soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon,该工具可以直接下载得到.使用tcpmon可以嗅探网络中传输的数据,便于我们更好的理解soap协议. 下载好tcpmon之后,打开该软件,如图简单设置 tcpmon相当于一个代理服务器,打开tcpmon后,如果把监听端口设置为9999,目标端口设置为8888,当用户访问9999端口时,消息会被tcp

Linux(CentOs6.6)系统学习笔记系列之二

上一篇博客主要是Linux系统的一些基本命令和介绍,然后这里介绍一些Linux系统的网络配置是如何操作的.配置IP地址信息...使用xshell工具进行远程管理linux.. 下面截了一些图: 1.输入setup进行安装 2.选择NetWork configuration 3.选择Device configuration 4.这里只有一块网卡eth0,我们选择eth0这块网卡进行配置Ip地址信息,直接按Enter键确认即可. 5.默认是星号(*)表示自动获取IP地址,类似于Windows中的自动

学习OpenCV的学习笔记系列(二)源码编译及自带样例工程

下载及安装CMake3.0.1 要自己编译OpenCV2.4.9的源码,首先,必须下载编译工具,使用的比较多的编译工具是CMake. 下面摘录一段关于CMake的介绍: CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程).他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C 特性,类似UNIX下的automake.只是 CMake 的组态档取名为 CmakeLists.txt.Cmake 并不直接建构出最终的软件,而是产生标准

python学习笔记系列----(二)控制流

实际开始看这一章节的时候,觉得都不想看了,因为每种语言都会有控制流,感觉好像我不看就会了似的.快速预览的时候,发现了原来还包含了对函数定义的一些描述,重点讲了3种函数形参的定义方法,章节的最后讲述了PEP8的一些重要的规范,在学习的过程中还是学到了些知识. 2.1  if 语句 if语句就不多说了,经常跟else if .. 和 else ..一起使用,如下所示: >>> x = int(raw_input("Please enter an integer: "))

USB2.0学习笔记连载(二):USB基础知识简介

  USB接口分为USB A型.USB B型.USBmini型.USBmicro型.USB3.0其中每种都有相应的插座和插头. 图1 图2 上图是USBA型接口,图1为插座,图2为插头.插座指向下行方向,插头指向上行方向. USB中一般常用有4根线,两边两根线一般为VBUS(5V的接入或接出线,对应上图中的1引脚)和GND(对应上图中的4引脚).中间两根为D+(对应上图中的3引脚),D-(对应上图中的2引脚),还有外加一个屏蔽层. 图3 图4 USB B型所对应的各信号和USB A型一致.在各种

JQuery学习笔记系列(二)----

jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多).其中也提供了很多函数来更加简洁的实现复杂的功能. 事件切换函数toggle(fn1,fn2,fn3 ...):作用是每次点击后依次调用函数,第一次点击调用fn1,第二次调用fn2,依次类推直到调用最后一个函数,然后继续重新开始从第一个继续开始 继续循环 <body> <ul> <li>Go to the store</li> <

操作系统学习笔记系列(二)-操作系统结构

1.操作系统为程序和用户提供了一定的服务. 1.用户界面 2.程序执行 3.I/O操作 4.文件系统操作 5.通信.在许多情况下一个进程需要与另一个进程交换信息.这种通信有两种方式.一种是发生在同一台计算机运行的两个进程之间,另外一种是运行在由网络连接起来的不同的计算机上的进程之间. 6.错误检测 7.资源分配 8.统计.需要记录哪些用户使用了多少和什么类型的资源 9.保护和安全.保护即确保所有对系统资源的访问是受控的,并且系统安全不受外界侵犯. 2.命令解释程序,比如linux中的shell,