Netty4.0学习笔记系列之四:混合使用coder和handler
Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它们的用法。
该例子模拟一个Server和Client,两者之间通过http协议进行通讯,在Server内部通过一个自定义的StringDecoder把httprequest转换成String。Server端处理完成后,通过StringEncoder把String转换成httpresponse,发送给客户端。具体的处理流程如图所示:
其中红色框中的Decoder、Encoder及request都是Netty框架自带的,灰色框中的三个类是我自己实现的。
Server端的类有:Server StringDecoder BusinessHandler StringEncoder四个类。
1、Server 启动netty服务,并注册handler、coder,注意注册的顺序:
- package com.guowl.testmulticoderandhandler;
- 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;
- import io.netty.handler.codec.http.HttpRequestDecoder;
- import io.netty.handler.codec.http.HttpResponseEncoder;
- // 测试coder 和 handler 的混合使用
- public class Server {
- 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 {
- // 都属于ChannelOutboundHandler,逆序执行
- ch.pipeline().addLast(new HttpResponseEncoder());
- ch.pipeline().addLast(new StringEncoder());
- // 都属于ChannelIntboundHandler,按照顺序执行
- ch.pipeline().addLast(new HttpRequestDecoder());
- ch.pipeline().addLast(new StringDecoder());
- ch.pipeline().addLast(new BusinessHandler());
- }
- }).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 {
- Server server = new Server();
- server.start(8000);
- }
- }
2、StringDecoder 把httpRequest转换成String,其中ByteBufToBytes是一个工具类,负责对ByteBuf中的数据进行读取
- package com.guowl.testmulticoderandhandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.HttpContent;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpRequest;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.guowl.utils.ByteBufToBytes;
- public class StringDecoder extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(StringDecoder.class);
- private ByteBufToBytes reader;
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("StringDecoder : msg's type is " + msg.getClass());
- if (msg instanceof HttpRequest) {
- HttpRequest request = (HttpRequest) msg;
- reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));
- }
- if (msg instanceof HttpContent) {
- HttpContent content = (HttpContent) msg;
- reader.reading(content.content());
- if (reader.isEnd()) {
- byte[] clientMsg = reader.readFull();
- logger.info("StringDecoder : change httpcontent to string ");
- ctx.fireChannelRead(new String(clientMsg));
- }
- }
- }
- }
3、BusinessHandler 具体处理业务的类,把客户端的请求打印出来,并向客户端发送信息
- package com.guowl.testmulticoderandhandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class BusinessHandler extends ChannelInboundHandlerAdapter {
- private Logger logger = LoggerFactory.getLogger(BusinessHandler.class);
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- String clientMsg = "client said : " + (String) msg;
- logger.info("BusinessHandler read msg from client :" + clientMsg);
- ctx.write("I am very OK!");
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
- }
4、StringEncoder 把字符串转换成HttpResponse
- package com.guowl.testmulticoderandhandler;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
- import static io.netty.handler.codec.http.HttpResponseStatus.OK;
- import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelOutboundHandlerAdapter;
- import io.netty.channel.ChannelPromise;
- import io.netty.handler.codec.http.DefaultFullHttpResponse;
- import io.netty.handler.codec.http.FullHttpResponse;
- import io.netty.handler.codec.http.HttpHeaders.Values;
- // 把String转换成httpResponse
- public class StringEncoder extends ChannelOutboundHandlerAdapter {
- private Logger logger = LoggerFactory.getLogger(StringEncoder.class);
- @Override
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- logger.info("StringEncoder response to client.");
- String serverMsg = (String) msg;
- FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(serverMsg
- .getBytes()));
- response.headers().set(CONTENT_TYPE, "text/plain");
- response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
- response.headers().set(CONNECTION, Values.KEEP_ALIVE);
- ctx.write(response);
- ctx.flush();
- }
- }
Client端有两个类:Client ClientInitHandler
1、Client 与Server端建立连接,并向Server端发送HttpRequest请求。
- package com.guowl.testmulticoderandhandler;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.buffer.Unpooled;
- 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;
- import io.netty.handler.codec.http.DefaultFullHttpRequest;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpMethod;
- import io.netty.handler.codec.http.HttpRequestEncoder;
- import io.netty.handler.codec.http.HttpResponseDecoder;
- import io.netty.handler.codec.http.HttpVersion;
- import java.net.URI;
- public class Client {
- 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 HttpResponseDecoder());
- ch.pipeline().addLast(new HttpRequestEncoder());
- ch.pipeline().addLast(new ClientInitHandler());
- }
- });
- // Start the client.
- ChannelFuture f = b.connect(host, port).sync();
- URI uri = new URI("http://127.0.0.1:8000");
- String msg = "Are you ok?";
- DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
- uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes()));
- request.headers().set(HttpHeaders.Names.HOST, host);
- request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
- request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
- f.channel().write(request);
- f.channel().flush();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- Client client = new Client();
- client.connect("127.0.0.1", 8000);
- }
- }
2、ClientInitHandler 从Server端读取响应信息
- package com.guowl.testmulticoderandhandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.HttpContent;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpResponse;
- import com.guowl.utils.ByteBufToBytes;
- public class ClientInitHandler extends ChannelInboundHandlerAdapter {
- private ByteBufToBytes reader;
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (msg instanceof HttpResponse) {
- HttpResponse response = (HttpResponse) msg;
- if (HttpHeaders.isContentLengthSet(response)) {
- reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));
- }
- }
- if (msg instanceof HttpContent) {
- HttpContent httpContent = (HttpContent) msg;
- ByteBuf content = httpContent.content();
- reader.reading(content);
- content.release();
- if (reader.isEnd()) {
- String resultStr = new String(reader.readFull());
- System.out.println("Server said:" + resultStr);
- }
- }
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.close();
- }
- }
工具类:ByteBufToBytes 对ByteBuf的数据进行读取,支持流式读取(reading 和 readFull方法结合使用)
ByteBufToBytes
- package com.guowl.utils;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- public class ByteBufToBytes {
- private ByteBuf temp;
- private boolean end = true;
- public ByteBufToBytes() {}
- public ByteBufToBytes(int length) {
- temp = Unpooled.buffer(length);
- }
- public void reading(ByteBuf datas) {
- datas.readBytes(temp, datas.readableBytes());
- if (this.temp.writableBytes() != 0) {
- end = false;
- } else {
- end = true;
- }
- }
- public boolean isEnd() {
- return end;
- }
- public byte[] readFull() {
- if (end) {
- byte[] contentByte = new byte[this.temp.readableBytes()];
- this.temp.readBytes(contentByte);
- this.temp.release();
- return contentByte;
- } else {
- return null;
- }
- }
- public byte[] read(ByteBuf datas) {
- byte[] bytes = new byte[datas.readableBytes()];
- datas.readBytes(bytes);
- return bytes;
- }
- }
运行结果:
2014-03-19 23:50:48 StringDecoder : msg's type is class io.netty.handler.codec.http.DefaultHttpRequest
2014-03-19 23:50:48 StringDecoder : msg's type is class io.netty.handler.codec.http.DefaultLastHttpContent
2014-03-19 23:50:48 StringDecoder : change httpcontent to string
2014-03-19 23:50:48 BusinessHandler read msg from client :client said : Are you ok?
2014-03-19 23:50:48 StringEncoder response to client.
可以看到执行顺序为:StringDecoder BusinessHandler StringEncoder ,其它的都是Netty自身的,没有打印。
通过该实例证明,Encoder、Decoder的本质也是Handler,它们的执行顺序、使用方法与Handler保持一致。
执行顺序是:Encoder 先注册的后执行,与OutboundHandler一致;Decoder是先注册的先执行,与InboundHandler一致。
Netty4.0学习笔记系列之四:混合使用coder和handler的更多相关文章
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序(转)
http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...
- Netty4.0学习笔记系列之三:构建简单的http服务(转)
http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.C ...
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- SQLServer学习笔记系列2
一.写在前面的话 继上一次SQLServer学习笔记系列1http://www.cnblogs.com/liupeng61624/p/4354983.html以后,继续学习Sqlserver,一步一步 ...
- 步步为营 SharePoint 开发学习笔记系列总结
转:http://www.cnblogs.com/springyangwc/archive/2011/08/03/2126763.html 概要 为时20多天的sharepoint开发学习笔记系列终于 ...
- WebService学习笔记系列(二)
soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...
- .NET CORE学习笔记系列(2)——依赖注入[5]: 创建一个简易版的DI框架[下篇]
为了让读者朋友们能够对.NET Core DI框架的实现原理具有一个深刻而认识,我们采用与之类似的设计构架了一个名为Cat的DI框架.在上篇中我们介绍了Cat的基本编程模式,接下来我们就来聊聊Cat的 ...
- .NET CORE学习笔记系列(2)——依赖注入【2】基于IoC的设计模式
原文:https://www.cnblogs.com/artech/p/net-core-di-02.html 正如我们在<控制反转>提到过的,很多人将IoC理解为一种“面向对象的设计模式 ...
随机推荐
- 查看library的依赖树
今天一同事问我如何解决包依赖重复的问题,我告诉他你可以用exclude,provide,compileOnly等关键字,他问我如何查找某个库依赖了什么,我说有一个插件,愣是想了好久没想起什么名字来,搜 ...
- opencv 彩色图像分割(inrange)
灰度图像大多通过算子寻找边缘和区域生长融合来分割图像. 彩色图像增加了色彩信息,可以通过不同的色彩值来分割图像,常用彩色空间HSV/HSI, RGB, LAB等都可以用于分割! 笔者主要介绍inran ...
- Ubuntu18.04安装和配置 Java JDK 和 JRE,并卸载自带OpenJDK
https://blog.csdn.net/freeking101/article/details/80522586
- MySQL的架构模型
看到大牛用户DB架构部的Keithlan<数据库性能优化之查询优化>,在学习过程发现很多不错的东西,就把它保存下来,分享给大家,因为作者说了一句很经典的话:“if you want to ...
- app后端设计-- 数据库分表
当项目上线后,随着用户的增长,有些数据表的规模会以几何级增长,当数据达到一定规模的时候(例如100万条),查询,读取性能就下降得很厉害,这时,我们就要考虑分表. 更新表数据时会导致索引更新,当单表数据 ...
- linux(CentOS) 下mysql自动备份
1.创建并编辑文件 /usr/sbin/bakmysql.sh,命令: vi /usr/sbin/bakmysql.sh 内容如下: db_user="root" db_passw ...
- Linux系统运维笔记(一),查看系统版本和设置系统时间
Linux系统运维笔记 查看系统版本和设置系统时间 查看系统版本 lsb_release -a (适用于所有的linux,包括Redhat.SuSE.Debian等发行版,但是在debian下要安装l ...
- 均方根误差(RMSE),平均绝对误差 (MAE),标准差 (Standard Deviation)
来源:https://blog.csdn.net/capecape/article/details/78623897 RMSE Root Mean Square Error, 均方根误差是观测值与真值 ...
- AIM Tech Round 4 (Div. 1) C - Upgrading Tree 构造 + 树的重心
C - Upgrading Tree 我发现我构造题好弱啊啊啊. 很明显能想到先找到重心, 然后我们的目标就是把所有点接到重心的儿子上,让重心的儿子子树变成菊花图, 这个先把重心到儿子的边连到 i , ...
- R语言编程艺术(5)R语言编程进阶
本文对应<R语言编程艺术> 第14章:性能提升:速度和内存: 第15章:R与其他语言的接口: 第16章:R语言并行计算 ================================== ...