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,注意注册的顺序:

  1. package com.guowl.testmulticoderandhandler;
  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. import io.netty.handler.codec.http.HttpRequestDecoder;
  11. import io.netty.handler.codec.http.HttpResponseEncoder;
  12. // 测试coder 和 handler 的混合使用
  13. public class Server {
  14. public void start(int port) throws Exception {
  15. EventLoopGroup bossGroup = new NioEventLoopGroup();
  16. EventLoopGroup workerGroup = new NioEventLoopGroup();
  17. try {
  18. ServerBootstrap b = new ServerBootstrap();
  19. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
  20. .childHandler(new ChannelInitializer<SocketChannel>() {
  21. @Override
  22. public void initChannel(SocketChannel ch) throws Exception {
  23. // 都属于ChannelOutboundHandler,逆序执行
  24. ch.pipeline().addLast(new HttpResponseEncoder());
  25. ch.pipeline().addLast(new StringEncoder());
  26. // 都属于ChannelIntboundHandler,按照顺序执行
  27. ch.pipeline().addLast(new HttpRequestDecoder());
  28. ch.pipeline().addLast(new StringDecoder());
  29. ch.pipeline().addLast(new BusinessHandler());
  30. }
  31. }).option(ChannelOption.SO_BACKLOG, 128)
  32. .childOption(ChannelOption.SO_KEEPALIVE, true);
  33. ChannelFuture f = b.bind(port).sync();
  34. f.channel().closeFuture().sync();
  35. } finally {
  36. workerGroup.shutdownGracefully();
  37. bossGroup.shutdownGracefully();
  38. }
  39. }
  40. public static void main(String[] args) throws Exception {
  41. Server server = new Server();
  42. server.start(8000);
  43. }
  44. }

2、StringDecoder 把httpRequest转换成String,其中ByteBufToBytes是一个工具类,负责对ByteBuf中的数据进行读取

  1. package com.guowl.testmulticoderandhandler;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.ChannelInboundHandlerAdapter;
  4. import io.netty.handler.codec.http.HttpContent;
  5. import io.netty.handler.codec.http.HttpHeaders;
  6. import io.netty.handler.codec.http.HttpRequest;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import com.guowl.utils.ByteBufToBytes;
  10. public class StringDecoder extends ChannelInboundHandlerAdapter {
  11. private static Logger   logger  = LoggerFactory.getLogger(StringDecoder.class);
  12. private ByteBufToBytes  reader;
  13. @Override
  14. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  15. logger.info("StringDecoder : msg's type is " + msg.getClass());
  16. if (msg instanceof HttpRequest) {
  17. HttpRequest request = (HttpRequest) msg;
  18. reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));
  19. }
  20. if (msg instanceof HttpContent) {
  21. HttpContent content = (HttpContent) msg;
  22. reader.reading(content.content());
  23. if (reader.isEnd()) {
  24. byte[] clientMsg = reader.readFull();
  25. logger.info("StringDecoder : change httpcontent to string ");
  26. ctx.fireChannelRead(new String(clientMsg));
  27. }
  28. }
  29. }
  30. }

3、BusinessHandler 具体处理业务的类,把客户端的请求打印出来,并向客户端发送信息

  1. package com.guowl.testmulticoderandhandler;
  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 BusinessHandler extends ChannelInboundHandlerAdapter {
  7. private Logger  logger  = LoggerFactory.getLogger(BusinessHandler.class);
  8. @Override
  9. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  10. String clientMsg = "client said : " + (String) msg;
  11. logger.info("BusinessHandler read msg from client :" + clientMsg);
  12. ctx.write("I am very OK!");
  13. }
  14. @Override
  15. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  16. ctx.flush();
  17. }
  18. }

4、StringEncoder 把字符串转换成HttpResponse

  1. package com.guowl.testmulticoderandhandler;
  2. import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
  3. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
  4. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
  5. import static io.netty.handler.codec.http.HttpResponseStatus.OK;
  6. import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import io.netty.buffer.Unpooled;
  10. import io.netty.channel.ChannelHandlerContext;
  11. import io.netty.channel.ChannelOutboundHandlerAdapter;
  12. import io.netty.channel.ChannelPromise;
  13. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  14. import io.netty.handler.codec.http.FullHttpResponse;
  15. import io.netty.handler.codec.http.HttpHeaders.Values;
  16. // 把String转换成httpResponse
  17. public class StringEncoder extends ChannelOutboundHandlerAdapter {
  18. private Logger  logger  = LoggerFactory.getLogger(StringEncoder.class);
  19. @Override
  20. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  21. logger.info("StringEncoder response to client.");
  22. String serverMsg = (String) msg;
  23. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(serverMsg
  24. .getBytes()));
  25. response.headers().set(CONTENT_TYPE, "text/plain");
  26. response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
  27. response.headers().set(CONNECTION, Values.KEEP_ALIVE);
  28. ctx.write(response);
  29. ctx.flush();
  30. }
  31. }

Client端有两个类:Client ClientInitHandler
1、Client 与Server端建立连接,并向Server端发送HttpRequest请求。

  1. package com.guowl.testmulticoderandhandler;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.handler.codec.http.DefaultFullHttpRequest;
  12. import io.netty.handler.codec.http.HttpHeaders;
  13. import io.netty.handler.codec.http.HttpMethod;
  14. import io.netty.handler.codec.http.HttpRequestEncoder;
  15. import io.netty.handler.codec.http.HttpResponseDecoder;
  16. import io.netty.handler.codec.http.HttpVersion;
  17. import java.net.URI;
  18. public class Client {
  19. public void connect(String host, int port) throws Exception {
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. Bootstrap b = new Bootstrap();
  23. b.group(workerGroup);
  24. b.channel(NioSocketChannel.class);
  25. b.option(ChannelOption.SO_KEEPALIVE, true);
  26. b.handler(new ChannelInitializer<SocketChannel>() {
  27. @Override
  28. public void initChannel(SocketChannel ch) throws Exception {
  29. ch.pipeline().addLast(new HttpResponseDecoder());
  30. ch.pipeline().addLast(new HttpRequestEncoder());
  31. ch.pipeline().addLast(new ClientInitHandler());
  32. }
  33. });
  34. // Start the client.
  35. ChannelFuture f = b.connect(host, port).sync();
  36. URI uri = new URI("http://127.0.0.1:8000");
  37. String msg = "Are you ok?";
  38. DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
  39. uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes()));
  40. request.headers().set(HttpHeaders.Names.HOST, host);
  41. request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
  42. request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
  43. f.channel().write(request);
  44. f.channel().flush();
  45. f.channel().closeFuture().sync();
  46. } finally {
  47. workerGroup.shutdownGracefully();
  48. }
  49. }
  50. public static void main(String[] args) throws Exception {
  51. Client client = new Client();
  52. client.connect("127.0.0.1", 8000);
  53. }
  54. }

2、ClientInitHandler 从Server端读取响应信息

  1. package com.guowl.testmulticoderandhandler;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import io.netty.handler.codec.http.HttpContent;
  6. import io.netty.handler.codec.http.HttpHeaders;
  7. import io.netty.handler.codec.http.HttpResponse;
  8. import com.guowl.utils.ByteBufToBytes;
  9. public class ClientInitHandler extends ChannelInboundHandlerAdapter {
  10. private ByteBufToBytes  reader;
  11. @Override
  12. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  13. if (msg instanceof HttpResponse) {
  14. HttpResponse response = (HttpResponse) msg;
  15. if (HttpHeaders.isContentLengthSet(response)) {
  16. reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));
  17. }
  18. }
  19. if (msg instanceof HttpContent) {
  20. HttpContent httpContent = (HttpContent) msg;
  21. ByteBuf content = httpContent.content();
  22. reader.reading(content);
  23. content.release();
  24. if (reader.isEnd()) {
  25. String resultStr = new String(reader.readFull());
  26. System.out.println("Server said:" + resultStr);
  27. }
  28. }
  29. }
  30. @Override
  31. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  32. ctx.close();
  33. }
  34. }

工具类:ByteBufToBytes 对ByteBuf的数据进行读取,支持流式读取(reading 和 readFull方法结合使用)
ByteBufToBytes

  1. package com.guowl.utils;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. public class ByteBufToBytes {
  5. private ByteBuf temp;
  6. private boolean end = true;
  7. public ByteBufToBytes() {}
  8. public ByteBufToBytes(int length) {
  9. temp = Unpooled.buffer(length);
  10. }
  11. public void reading(ByteBuf datas) {
  12. datas.readBytes(temp, datas.readableBytes());
  13. if (this.temp.writableBytes() != 0) {
  14. end = false;
  15. } else {
  16. end = true;
  17. }
  18. }
  19. public boolean isEnd() {
  20. return end;
  21. }
  22. public byte[] readFull() {
  23. if (end) {
  24. byte[] contentByte = new byte[this.temp.readableBytes()];
  25. this.temp.readBytes(contentByte);
  26. this.temp.release();
  27. return contentByte;
  28. } else {
  29. return null;
  30. }
  31. }
  32. public byte[] read(ByteBuf datas) {
  33. byte[] bytes = new byte[datas.readableBytes()];
  34. datas.readBytes(bytes);
  35. return bytes;
  36. }
  37. }

运行结果:

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的更多相关文章

  1. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

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

    http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...

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

    http://blog.csdn.net/u013252773/article/details/21254257 本文主要介绍如何通过Netty构建一个简单的http服务. 想要实现的目的是: 1.C ...

  4. Netty4.0学习笔记系列之二:Handler的执行顺序

    Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...

  5. SQLServer学习笔记系列2

    一.写在前面的话 继上一次SQLServer学习笔记系列1http://www.cnblogs.com/liupeng61624/p/4354983.html以后,继续学习Sqlserver,一步一步 ...

  6. 步步为营 SharePoint 开发学习笔记系列总结

    转:http://www.cnblogs.com/springyangwc/archive/2011/08/03/2126763.html 概要 为时20多天的sharepoint开发学习笔记系列终于 ...

  7. WebService学习笔记系列(二)

    soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...

  8. .NET CORE学习笔记系列(2)——依赖注入[5]: 创建一个简易版的DI框架[下篇]

    为了让读者朋友们能够对.NET Core DI框架的实现原理具有一个深刻而认识,我们采用与之类似的设计构架了一个名为Cat的DI框架.在上篇中我们介绍了Cat的基本编程模式,接下来我们就来聊聊Cat的 ...

  9. .NET CORE学习笔记系列(2)——依赖注入【2】基于IoC的设计模式

    原文:https://www.cnblogs.com/artech/p/net-core-di-02.html 正如我们在<控制反转>提到过的,很多人将IoC理解为一种“面向对象的设计模式 ...

随机推荐

  1. 移动端调试利器之vconsole

    说明 由于移动端项目在手机中调试时不能使用chrome的控制台,而vconsole是对pc端console的改写 使用方法 使用 npm 安装: npm install vconsole 使用webp ...

  2. 【linux】环境变量

    参考链接: http://www.cnblogs.com/growup/archive/2011/07/02/2096142.html https://zhidao.baidu.com/questio ...

  3. appium入门级教程(1)—— appium介绍

    appium介绍 官方网站与介绍 1.特点 appium 是一个自动化测试开源工具,支持 iOS 平台和 Android 平台上的原生应用,web应用和混合应用. “移动原生应用”是指那些用iOS或者 ...

  4. Java第三阶段学习(九、类加载器、反射)

    一.类加载器 1.类的加载: 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化. 1.1 加载: 就是指将class文件读入内存,并为之自动 ...

  5. Vue.js开始第一个项目

    前端架构之路:使用Vue.js开始第一个项目   Vue.js做为目前前端最热门的库之一,为快速构建并开发前端项目多了一种思维模式.本文通过一个简单的实例开始上手Vue.js开发. 一.技术准备 使用 ...

  6. 039 DataFrame的理解

    1.构成 由RDD+Schema构成 RDD: DataFrame中的数据 ===> df.rdd Schema: RDD中数据的结构 ===> df.schema df是dataFram ...

  7. 001.LVM简介

    一 概念 LVM是 Logical Volume Manager(逻辑卷管理)的简写,它由Heinz Mauelshagen在Linux 2.4内核上实现.LVM将一个或多个硬盘的分区在逻辑上集合,相 ...

  8. 用户 'IIS APPPOOL\DefaultAppPool' 登录失败【收藏】

    转载:http://blog.csdn.net/wenjie315130552/article/details/7246143 问题是应用程序连接池的问题.网上有些朋友说是Temp文件夹的权限的问题. ...

  9. 青客宝团队Consul内部分享ppt

    青客宝团队Consul内部分享ppt   https://mp.weixin.qq.com/s?src=3&timestamp=1503647705&ver=1&signatu ...

  10. spring cloud 学习(11) - 用fastson替换jackson及用gb2312码输出

    前几天遇到一个需求,因为要兼容旧项目的编码格式,需要spring-cloud的rest接口,输出gb2312编码,本以为是一个很容易的事情,比如下面这样: @RequestMapping(method ...