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

[java] view plaincopy
  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中的数据进行读取

[java] view plaincopy
  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 具体处理业务的类,把客户端的请求打印出来,并向客户端发送信息

[java] view plaincopy
  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

[java] view plaincopy
  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请求。

[java] view plaincopy
  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端读取响应信息

[java] view plaincopy
  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

[java] view plaincopy
  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. SQL Server 2008/2012中SQL应用系列及BI学习笔记系列--目录索引

    SQL Server 2008中的一些特性总结及BI学习笔记系列,欢迎与邀月交流. 3w@live.cn  ◆0.SQL应用系列 1.SQL Server 2008中SQL增强之一:Values新用途 ...

  2. 进程——Windows核心编程学习手札系列之四

    进程 --Windows核心编程学习手札系列之四 进程是一个正在运行的程序的实例,有两个部分组成:一个是操作系统用来管理进程的内核对象,内核对象是系统用来存放关于进程的统计信息的地方:另一个是地址空间 ...

  3. SQLServer学习笔记系列2

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

  4. CCC3.0学习笔记_认证和隐私保护

    CCC3.0学习笔记_Authentication and Privacy Keys 系列文章目录 文章目录 系列文章目录 前言 1. 手机端和车厂服务器端的密钥存储 2. 密钥的产生和使用的说明 3 ...

  5. CodeMonkey过关学习笔记系列:46-55关 数组

    CodeMonkey过关学习笔记系列:46-55关 •"数组"索引 (ARRAY INDEXING) 46~55 第 46 关挑战 当我们有一根以上的香蕉时,我们可以用 [] 这个 ...

  6. CodeMonkey过关学习笔记系列:71-85关 函数

    CodeMonkey过关学习笔记系列:71-75关 •"函数"农场 (FUNCTION FARM) 71 ~ 85 第 71 关挑战 "函数"农场step di ...

  7. CCC3.0学习笔记_数字密钥数据结构

    CCC3.0学习笔记_数字密钥数据结构 系列文章目录 文章目录 系列文章目录 前言 4.1 Applet Instance Layout 4.2 Digital Key Structure 4.2.1 ...

  8. CCC3.0学习笔记_证书数据

    CCC3.0学习笔记_证书数据 系列文章目录 文章目录 系列文章目录 前言 1. [A] - SE Root CA Certificate 2. [B] - SE Root Certificate 3 ...

  9. 自动控制原理学习笔记系列( 一、自动控制系统的稳定性分析)

    自动控制原理学习笔记系列 第一篇 自动控制系统的稳定性分析 自动控制原理学习笔记系列 一.目的 二.操作步骤 1. 研究高阶系统的稳定性 2.系统根轨迹增益变化对系统稳定性的影响 一.目的 (1) 研 ...

  10. C++菜鸟学习笔记系列(3)——基本内置类型的使用

    C++菜鸟学习笔记系列(3) (前两天比较忙,没有进行更新,今天及时又写了一篇) 本期主题:C++中基本内置类型的使用. 与C语言类似的C++也定义了一套包括算术类型和空类型在内的基本数据类型,其中算 ...

最新文章

  1. Codeforces Round #653 (Div. 3)部分题解
  2. 防止一个进程被多次启动
  3. varnishtop中文man page
  4. Internet Explorer 8 Beta2 常见问题解答
  5. JVM调优实战:G1中的to-space exhausted问题
  6. python绘制随机数直方图-用matplotlib画直方图(histogram)
  7. 微软向.NET开发者开放Windows Phone 7 Market
  8. golang实现图片上传和下载
  9. HIbernate的优缺点
  10. JavaScript substr() 方法
  11. tomcat与apache的面试题
  12. String Statistics(2008年珠海市ACM程序设计竞赛)
  13. Apache的Mod_rewrite学习(RewriteRule重写规则的语法)
  14. 宝元系统通讯软件recon_企业即时通讯工具需注意哪些问题
  15. JDK 8.0 新特性——函数式接口和Lambda 表达式
  16. 央行数字货币(CBDC)基础知识
  17. python图像灰度化、二值化
  18. C++ Opencv安装学习笔记
  19. 跟熊浩学沟通30讲读后感_跟熊浩学沟通
  20. w7电脑蓝屏怎么解决_电脑突然蓝屏,教您电脑突然蓝屏怎么解决

热门文章

  1. 阶段3 1.Mybatis_11.Mybatis的缓存_8 mybatis的二级缓存
  2. 电影图标:杀死比尔(Kil Bill)
  3. Web.xml in Hello1 project
  4. 信息管理与信息系统专业渊源
  5. 基本数据类型-列表_元组_字典
  6. 洛谷 P1114 “非常男女”计划
  7. HTML基础学习(二)—CSS
  8. 转载:向 XPath 中添加自定义函数
  9. antd的Tree控件实现点击展开功能
  10. 神奇的python系列11:函数之生成器,列表推导式