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 代码如下
- package com.guowl.testmultihandler;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- public class HelloServer {
- public void start(int port) throws Exception {
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1
- ch.pipeline().addLast(new OutboundHandler1());
- ch.pipeline().addLast(new OutboundHandler2());
- // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2
- ch.pipeline().addLast(new InboundHandler1());
- ch.pipeline().addLast(new InboundHandler2());
- }
- }).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();
- }
- }
- public static void main(String[] args) throws Exception {
- HelloServer server = new HelloServer();
- server.start(8000);
- }
- }
2、InboundHandler1
- package com.guowl.testmultihandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class InboundHandler1 extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(InboundHandler1.class);
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("InboundHandler1.channelRead: ctx :" + ctx);
- // 通知执行下一个InboundHandler
- ctx.fireChannelRead(msg);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- logger.info("InboundHandler1.channelReadComplete");
- ctx.flush();
- }
- }
3、InboundHandler2
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class InboundHandler2 extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(InboundHandler2.class);
- @Override
- // 读取Client发送的信息,并打印出来
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("InboundHandler2.channelRead: ctx :" + ctx);
- ByteBuf result = (ByteBuf) msg;
- byte[] result1 = new byte[result.readableBytes()];
- result.readBytes(result1);
- String resultStr = new String(result1);
- System.out.println("Client said:" + resultStr);
- result.release();
- ctx.write(msg);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- logger.info("InboundHandler2.channelReadComplete");
- ctx.flush();
- }
- }
4、OutboundHandler1
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelOutboundHandlerAdapter;
- import io.netty.channel.ChannelPromise;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(OutboundHandler1.class);
- @Override
- // 向client发送消息
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- 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();
- }
- }
5、OutboundHandler2
- package com.guowl.testmultihandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelOutboundHandlerAdapter;
- import io.netty.channel.ChannelPromise;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(OutboundHandler2.class);
- @Override
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- logger.info("OutboundHandler2.write");
- // 执行下一个OutboundHandler
- super.write(ctx, msg, promise);
- }
- }
Client端有两个类:HelloClient HelloClientIntHandler
1、HelloClient
- package com.guowl.testmultihandler;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- public class HelloClient {
- public void connect(String host, int port) throws Exception {
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- Bootstrap b = new Bootstrap();
- b.group(workerGroup);
- b.channel(NioSocketChannel.class);
- b.option(ChannelOption.SO_KEEPALIVE, true);
- b.handler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new HelloClientIntHandler());
- }
- });
- // Start the client.
- ChannelFuture f = b.connect(host, port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- HelloClient client = new HelloClient();
- client.connect("127.0.0.1", 8000);
- }
- }
2、HelloClientIntHandler
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(HelloClientIntHandler.class);
- @Override
- // 读取服务端的信息
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("HelloClientIntHandler.channelRead");
- ByteBuf result = (ByteBuf) msg;
- byte[] result1 = new byte[result.readableBytes()];
- result.readBytes(result1);
- result.release();
- ctx.close();
- System.out.println("Server said:" + new String(result1));
- }
- @Override
- // 当连接建立的时候向服务端发送消息 ,channelActive 事件当连接建立的时候会触发
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- 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();
- }
- }
server端执行结果为:
在使用Handler的过程中,需要注意:
1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
Netty4.0学习笔记系列之二:Handler的执行顺序(转)的更多相关文章
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- Netty4.0学习笔记系列之四:混合使用coder和handler
Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它 ...
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
- Netty4.0学习笔记系列之三:构建简单的http服务(转)
http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.C ...
- WebService学习笔记系列(二)
soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...
- Java学习笔记 - 类方法与代码块的执行顺序
类的初始化顺序 使用一个简单的父子类例子来做示范,代码执行顺序在代码后有标注. class Parent { public static String p_StaticField = "父类 ...
- python学习笔记系列----(二)控制流
实际开始看这一章节的时候,觉得都不想看了,因为每种语言都会有控制流,感觉好像我不看就会了似的.快速预览的时候,发现了原来还包含了对函数定义的一些描述,重点讲了3种函数形参的定义方法,章节的最后讲述了P ...
- USB2.0学习笔记连载(二):USB基础知识简介
USB接口分为USB A型.USB B型.USBmini型.USBmicro型.USB3.0其中每种都有相应的插座和插头. 图1 图2 上图是USBA型接口,图1为插座,图2为插头.插座指向下行方向, ...
- JQuery学习笔记系列(二)----
jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多).其中也提供了很多函数来更加简洁的实现复杂的功能. 事件切换函数toggle ...
随机推荐
- android 10 事件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layo ...
- android 05 桢布局:FrameLayout 网格布据 GridLayout
xml文件: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android: ...
- systemTAP 学习
http://blog.csdn.net/moonvs2010/article/category/1570309
- JTA 深度历险 - 原理与实现---转
利用 JTA 处理事务 什么是事务处理 事务是计算机应用中不可或缺的组件模型,它保证了用户操作的原子性 ( Atomicity ).一致性 ( Consistency ).隔离性 ( Isolatio ...
- HTTP协议基础与实验
一. HTTP协议(Hypetext Transfer Protoacal,超文本传输协议) HTTP协议规定了Web基本的运作过程,以及Web服务器之间的通信细节. Http协议采用客户端/服务器端 ...
- 17、SQL Server 备份和还原
SQL Server 备份 恢复模式 SQL Server 数据恢复模式分为三种:完整恢复模式.大容量日志恢复模式.简单恢复模式. 完整恢复模式 默认的恢复模式,它会完整记录下操作数据库的每一个步骤, ...
- 点击其它地方隐藏div/事件冒泡/sweet-alert阻止冒泡
点击document时把div隐藏,但点击div时阻止点击事件冒泡到document,从而实现“点击文档其它地方隐藏div,点击div本身不隐藏”.js代码如下:$("#div") ...
- opencart 模块开发详解
opencart 模块开发详解 由 xiekanxiyang » 2013年 7月 11日 10:17 pm opencart 将页面分成若干模块, 每个模块可以有多个实例(可能这样说不是很恰当) 每 ...
- Ubuntu系统中安装RPM格式包的方法
Ubuntu的软件包格式为deb,而RPM格式的包则是Red Hat 相关系统所用的软件包.当我们看到一个想用的软件包时,如果他是RPM格式,而你的操作系统是Ubuntu,那岂不是很遗憾?其实,在Ub ...
- CSS实现图片在div a标签中水平垂直居中
CSS实现图片在div a标签中水平垂直居中 <div class="demo"> <a href="#"> <img src=& ...