netty4 Handler的执行顺序
转载:https://my.oschina.net/jamaly/blog/272385
Handler在netty中,无疑占据着非常重要的地位。Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。
Netty中的所有handler都实现自ChannelHandler接口。按照输出输出来分,分为ChannelInboundHandler、ChannelOutboundHandler两大类。ChannelInboundHandler对从客户端发往服务器的报文进行处理,一般用来执行解码、读取客户端数据、进行业务处理等;ChannelOutboundHandler对从服务器发往客户端的报文进行处理,一般用来进行编码、发送报文到客户端。
Netty中,可以注册多个handler。ChannelInboundHandler按照注册的先后顺序执行;ChannelOutboundHandler按照注册的先后顺序逆序执行,如下图所示,按照注册的先后顺序对Handler进行排序,request进入Netty后的执行顺序为:
下面例子涉及的类包括:
一、HelloServer:
package com.yao.nettyhandler;
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);
}
}
二、InboundHandler1:
package com.yao.nettyhandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class InboundHandler1 extends ChannelInboundHandlerAdapter {
private static Log logger = LogFactory.getLog(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();
}
}
三、InboundHandler2:
package com.yao.nettyhandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class InboundHandler2 extends ChannelInboundHandlerAdapter {
private static Log logger = LogFactory.getLog(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();
}
}
四、OutboundHandler1 :
package com.yao.nettyhandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
private static Log logger = LogFactory.getLog(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();
}
}
五、OutboundHandler2:
package com.yao.nettyhandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
private static Log logger = LogFactory.getLog(OutboundHandler2.class);
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
logger.info("OutboundHandler2.write");
// 执行下一个OutboundHandler
super.write(ctx, msg, promise);
}
}
下面是客户端
六、HelloClient:
package com.yao.nettyhandler;
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);
}
}
七、HelloClientIntHandler:
package com.yao.nettyhandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
private static Log logger = LogFactory.getLog(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();
}
}
八、总结:
在使用Handler的过程中,需要注意:
1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
2、ChannelOutboundHandler中,ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
4、Handler的消费处理放在最后一个处理。
netty4 Handler的执行顺序的更多相关文章
- hadoop27---netty中handler的执行顺序
Netty是基于Java NIO的网络应用框架. Netty是一个NIO client-server(客户端服务器)框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议.Netty提供了一 ...
- 7.Netty中 handler 的执行顺序
1.Netty中handler的执行顺序 Handler在Netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序(转)
http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- netty(七) Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- 关于Netty Pipeline中Handler的执行顺序问题
原文地址:http://blog.csdn.net/wgyvip/article/details/25637651 最近在学习Netty框架,根据官网的教程学着做了几个小测试,都成功了,后面开始试着写 ...
- netty4.1.32 pipeline的添加顺序和执行顺序
本文只想讨论一下pipeline的执行顺序问题,因为这个搞不明白就不知道先添加编码还是解码,是不是可以混淆添加等等一系列事情 pipeline.addLast(new outboundsHandler ...
- 【转】netty4.1.32 pipeline的添加顺序和执行顺序
原文:https://www.cnblogs.com/ruber/p/10186571.html 本文只想讨论一下pipeline的执行顺序问题,因为这个搞不明白就不知道先添加编码还是解码,是不是可以 ...
- javascript中的事件冒泡、事件捕获和事件执行顺序
谈起JavaScript的 事件,事件冒泡.事件捕获.阻止默认事件这三个话题,无论是面试还是在平时的工作中,都很难避免. DOM事件标准定义了两种事件流,这两种事件流有着显著的不同并且可能对你的应用有 ...
随机推荐
- python_way ,day5 模块,模块3 ,双层装饰器,字符串格式化,生成器,递归,模块倒入,第三方模块倒入,序列化反序列化,日志处理
python_way.day5 1.模块3 time,datetime, json,pickle 2.双层装饰器 3.字符串格式化 4.生成器 5.递归 6.模块倒入 7.第三方模块倒入 8.序列化反 ...
- 不同浏览器对document.documentElement和document.body的scrollheight ,scrollTop,clientHeight以及判断滚动条是否滚动到页面最底部 【转载】
前段时间学习怎么写一个瀑布流的时候,就接触到document.documentElement和document.body的区别,然后今天查资料的时候看到这篇博客,遂转载记录在此. 两种特殊的文档属性可 ...
- centos下安装nginx和php-fpm
安装这两个花了大约七个小时,简直呵呵,安装nginx就是直接 yum install nginx ,但发现一打开php文件就是直接下载该php文件,也就是不能识别php文件,解决这个花了好久,但其实看 ...
- iOS - OC RunLoop 运行循环/消息循环
1.RunLoop 1)运行循环: 运行循环在 iOS 开发中几乎不用,但是概念的理解却非常重要. 同一个方法中的代码一般都在同一个运行循环中执行,运行循环监听 UI 界面的修改事件,待本次运行循环结 ...
- OC拓展(category)
1. 扩展类的功能Category提供了一种比继承(inheritance)更为简洁的方法来对class进行扩展,我们可以为任何已经存在的class添加方法(不包括数据成员)却不需要访问该class的 ...
- windos多线程编程
随机数滚动发生器 #include <stdio.h> #include <Windows.h> #include <ctime> #include <pro ...
- 09 高效的PL/SQL程序设计
程序包 Package 断开了依赖链 实验依赖关系: <1> 首先不使用包 -- 创建表 CREATE table t (x int); -- 创建视图 create view v as ...
- Oracle一列的多行数据拼成一行显示字符
Oracle一列的多行数据拼成一行显示字符 oracle 提供了两个函数WMSYS.WM_CONCAT 和 ListAgg函数. www.2cto.com 先介绍:WMSYS.WM_CO ...
- Centos升级Python及pip
因为CentOS系统中旧版本的Python已被深度依赖,所以不能卸载原有的Python,只能全新安装. 1.从官网下载: wget https://www.python.org/ftp/python/ ...
- uva 11324 The Largest Clique
vjudge 上题目链接:uva 11324 scc + dp,根据大白书上的思路:" 同一个强连通分量中的点要么都选,要么不选.把强连通分量收缩点后得到SCC图,让每个SCC结点的权等于它 ...