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. [原创]Sql2008 使用TVP批量插入数据

    TVP(全称 :Table-Valued Parameter) 叫做表值参数(Table-Valued Parameter)是SQL2008的一个新特性.顾名思义,表值参数表示你可以把一个表类型作为参 ...

  2. window BIOS设置硬盘启动模式

      bios如何设置硬盘启动模式?BIOSD硬盘模试主是要针对IDE接口的硬盘和SATA接口的硬盘来设置的.以前的主板只支持一种类型.现在的智能笔记本主板支持:IDE Mode.AHCI Mode.下 ...

  3. Python PIL: cannot write mode RGBA as BMP(把有四位通道(RGBA)的图片换成有三位通道的(RGA))

    图片png结尾的有四个通道RGBA,把四个通道改为三个通道(RGB),如下,bg为修改后的图片 img = Image.open('pic\\find.png')bg = Image.new(&quo ...

  4. NOIP2018 货币系统

    题面 思路 先分析一下,a集合的子集肯定不存在可以用它来表示的数,a集合是不能够表示的. 所以问题简化了成为选出a的一个子集(个数最少),能够表达a集合所有能表达的数. 接下来继续分析 如:1 2 4 ...

  5. Java编程的逻辑 (26) - 剖析包装类 (上)

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  6. Java编程的逻辑 (71) - 显式锁

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  7. 如何写django中form的测试用例

    可简可繁, 可插库,可字符, 要测试valid,也要测试invalid, 可用csrf,也可用context. 放一个全面的, 实践中,找一个最优的组合就好. class NewTopicTests( ...

  8. vSphere Web Client 6.5 如何上传ISO文件

    vSphere Web Client 6.5 如何上传ISO文件? 1,先开启SSH功能. WEB登陆管理端,选中一台主机,配置-安全配置文件-服务编辑-SSH项-起动. 2,用SFTP上传ISO文件 ...

  9. Redux 和 ngrx 创建更佳的 Angular 2

    Redux 和 ngrx 创建更佳的 Angular 2 翻译:使用 Redux 和 ngrx 创建更佳的 Angular 2 原文地址:http://onehungrymind.com/build- ...

  10. 【AtCoder】ARC087

    C - Good Sequence 题解 用个map愉悦一下就好了 代码 #include <bits/stdc++.h> #define fi first #define se seco ...