昨天晚上在看到7.2章MessagePack编码器和解码器开发这一章时,书里面没有贴出全部的代码,然后我按照我自己的想法把代码补全后,发现死活没有把代码跑通。

然后花了挺多时间在网上找,很多博客都贴出了这一节的代码,但是基本上都是把书上有的给贴出来了,严重怀疑他们敲完代码后有没有跑一遍。

不过最后还是找到了一个博客里面贴全了代码,发现是UserInfo类里面缺了一个注解@Message导致代码没跑通的。

Netty使用MessagePack首先自定义编解码器

下面贴上全部代码

UserInfo.java

  1. package MessagePack;
  2.  
  3. import org.msgpack.annotation.Message;
  4.  
  5. @Message
  6. public class UserInfo
  7. {
  8. private int age;
  9.  
  10. private String name;
  11.  
  12. public int getAge() {
  13. return age;
  14. }
  15.  
  16. public void setAge(int age) {
  17. this.age = age;
  18. }
  19.  
  20. public String getName() {
  21. return name;
  22. }
  23.  
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27.  
  28. @Override
  29. public String toString()
  30. {
  31. return "age = " + age + "; name = " + name;
  32. }
  33. }

MsgpackDecoder.java

  1. package MessagePack;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.MessageToMessageDecoder;
  6. import org.msgpack.MessagePack;
  7.  
  8. import java.util.List;
  9.  
  10. public class MsgpackDecoder extends MessageToMessageDecoder<ByteBuf>
  11. {
  12. protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception
  13. {
  14. final byte[] array;
  15. final int length = byteBuf.readableBytes();
  16. array = new byte[length];
  17. byteBuf.getBytes(byteBuf.readerIndex(), array, 0, length);
  18. MessagePack msgpack = new MessagePack();
  19. list.add(msgpack.read(array));
  20. }
  21. }

MsgpackEncoder.java

  1. package MessagePack;
  2.  
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.MessageToByteEncoder;
  6. import org.msgpack.MessagePack;
  7.  
  8. public class MsgpackEncoder extends MessageToByteEncoder<Object>
  9. {
  10. protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception
  11. {
  12. MessagePack msgpack = new MessagePack();
  13. byte[] raw = msgpack.write(o);
  14. byteBuf.writeBytes(raw);
  15. }
  16. }

EchoServer.java

  1. package MessagePack;
  2.  
  3. import io.netty.bootstrap.ServerBootstrap;
  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.NioServerSocketChannel;
  11.  
  12. public class EchoServer
  13. {
  14. private final int port;
  15.  
  16. public EchoServer(int port)
  17. {
  18. this.port = port;
  19. }
  20.  
  21. public void bind() throws Exception
  22. {
  23. //配置服务端的NIO线程
  24. EventLoopGroup bossGroup = new NioEventLoopGroup();
  25. EventLoopGroup workerGroup = new NioEventLoopGroup();
  26. try
  27. {
  28. ServerBootstrap b = new ServerBootstrap();
  29. b.group(bossGroup,workerGroup)
  30. .channel(NioServerSocketChannel.class)
  31. .option(ChannelOption.SO_BACKLOG, 100)
  32. //.handler(new LoggingHandler(LogLevel.INFO))
  33. .childHandler(new ChannelInitializer<SocketChannel>()
  34. {
  35. @Override
  36. protected void initChannel(SocketChannel socketChannel) throws Exception
  37. {
  38. socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
  39. socketChannel.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
  40. socketChannel.pipeline().addLast(new EchoServerHandler());
  41. }
  42. });
  43. //绑定端口,同步等待成功
  44. ChannelFuture f = b.bind(port).sync();
  45.  
  46. //等待服务端监听端口关闭
  47. System.out.println("bind");
  48. f.channel().closeFuture().sync();
  49. System.out.println("close");
  50. }
  51. finally
  52. {
  53. //优雅退出,释放线程池资源
  54. bossGroup.shutdownGracefully();
  55. workerGroup.shutdownGracefully();
  56. }
  57. }
  58.  
  59. public static void main(String[] args) throws Exception
  60. {
  61. int port = 22233;
  62. if (null != args && args.length > 0)
  63. {
  64. try
  65. {
  66. port = Integer.parseInt(args[0]);
  67. }
  68. catch (Exception e)
  69. {
  70. port = 22233;
  71. }
  72. }
  73.  
  74. new EchoServer(port).bind();
  75. }
  76. }

EchoServerHandler.java

  1. package MessagePack;
  2.  
  3. import io.netty.channel.ChannelHandlerAdapter;
  4. import io.netty.channel.ChannelHandlerContext;
  5.  
  6. public class EchoServerHandler extends ChannelHandlerAdapter
  7. {
  8. @Override
  9. public void channelActive(ChannelHandlerContext ctx)
  10. {
  11. System.out.println("channelActive");
  12. }
  13.  
  14. @Override
  15. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
  16. {
  17. System.out.println("Server receive the mspack message : " + msg);
  18. ctx.writeAndFlush(msg);
  19. }
  20.  
  21. @Override
  22. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  23. {
  24. System.out.println(cause.getMessage());
  25. ctx.close();
  26. }
  27. }

EchoClient.java

  1. package MessagePack;
  2.  
  3. import io.netty.bootstrap.Bootstrap;
  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.  
  12. public class EchoClient
  13. {
  14. private final String host;
  15. private final int port;
  16. private final int sendNumber;
  17.  
  18. public EchoClient(String host, int port, int sendNumber)
  19. {
  20. this.host = host;
  21. this.port = port;
  22. this.sendNumber = sendNumber;
  23. }
  24.  
  25. public void connect() throws Exception
  26. {
  27. //配置客户端NIO线程组
  28. EventLoopGroup group = new NioEventLoopGroup();
  29. try
  30. {
  31. Bootstrap b = new Bootstrap();
  32. b.group(group).channel(NioSocketChannel.class)
  33. .option(ChannelOption.TCP_NODELAY, true)
  34. .handler(new ChannelInitializer<SocketChannel>()
  35. {
  36. protected void initChannel(SocketChannel socketChannel) throws Exception
  37. {
  38. socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
  39. socketChannel.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
  40. socketChannel.pipeline().addLast(new EchoClientHandler(sendNumber));
  41. }
  42. });
  43. //发起异步连接操作
  44. ChannelFuture f = b.connect(host, port).sync();
  45.  
  46. System.out.println("connect");
  47. //等待客户端链路关闭
  48. f.channel().closeFuture().sync();
  49. System.out.println("close");
  50. }
  51. finally
  52. {
  53. //优雅退出,释放NIO线程组
  54. group.shutdownGracefully();
  55. }
  56. }
  57.  
  58. public static void main(String[] args) throws Exception
  59. {
  60. int port = 22233;
  61. if (null != args && args.length > 0)
  62. {
  63. try
  64. {
  65. port = Integer.parseInt(args[0]);
  66. }
  67. catch (Exception e)
  68. {
  69. port = 22233;
  70. }
  71. }
  72.  
  73. new EchoClient("127.0.0.1", 22233, 100).connect();
  74. }
  75. }

EchoClientHandler.java

  1. package MessagePack;
  2.  
  3. import io.netty.channel.ChannelHandlerAdapter;
  4. import io.netty.channel.ChannelHandlerContext;
  5.  
  6. public class EchoClientHandler extends ChannelHandlerAdapter
  7. {
  8. private final int sendNumber;
  9.  
  10. public EchoClientHandler(int sendNumber)
  11. {
  12. this.sendNumber = sendNumber;
  13. }
  14.  
  15. @Override
  16. public void channelActive(ChannelHandlerContext ctx)
  17. {
  18. System.out.println("channelActive");
  19. // ByteBuf byteBuf = Unpooled.copiedBuffer("asdf".getBytes());
  20. // ctx.writeAndFlush(byteBuf);
  21.  
  22. UserInfo[] infos = UserInfo();
  23. for (UserInfo infoE : infos)
  24. {
  25. ctx.write(infoE);
  26. }
  27. ctx.flush();
  28. }
  29.  
  30. private UserInfo[] UserInfo()
  31. {
  32. UserInfo[] userInfos = new UserInfo[sendNumber];
  33. UserInfo userInfo = null;
  34. for (int i=0; i < sendNumber; i++)
  35. {
  36. userInfo = new UserInfo();
  37. userInfo.setAge(i);
  38. userInfo.setName("ABCDEFG --->" + i);
  39. userInfos[i] = userInfo;
  40. }
  41. return userInfos;
  42. }
  43.  
  44. @Override
  45. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
  46. {
  47. System.out.println("Client receive the msgpack message : " + msg);
  48. //ctx.write(msg);
  49. }
  50.  
  51. @Override
  52. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
  53. {
  54. ctx.flush();
  55. }
  56. }

netty学习记录2的更多相关文章

  1. netty 学习记录一

    近期在学习netty相关知识,认为<netty 权威指南>这本书还是挺好的,适合我这样的刚開始学习的人.加上netty本身自带的很多样例,学起来还是挺有兴趣的.简单记录下, 一般serve ...

  2. netty学习记录1

    最近在学习netty,看的是<netty权威指南 第2版>. 然后看的同时也把书上面的代码一行行敲下来做练习,不过到第三章就出问题了. 按照书上讲的,sever/client端都需要继承C ...

  3. Netty学习记录

    一.Netty简介 Netty 是一个基于 JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性. Netty 是一个 NIO client-s ...

  4. Netty学习记录-入门篇

    你如果,缓缓把手举起来,举到顶,再突然张开五指,那恭喜你,你刚刚给自己放了个烟花. 模块介绍 netty-bio: 阻塞型网络通信demo. netty-nio: 引入channel(通道).buff ...

  5. Netty 学习 一、初识Netty【原创】

    在过去几年的工作和学习中,比较关注高层次的应用开发,对底层探究较少.实现Web应用的开发,主要依赖Tomcat.Apache等应用服务器,程序员无需了解底层协议,但同样限制了应用的性能和效率.现在开始 ...

  6. java后端学习记录2019

    学习计划 2019年计划 1.学习计算机基础,并加以实践.包括LeetCode刷题.数据库原理(索引和锁.Sql优化等).网络协议(Http.Tcp).操作系统(加深Linux).<Http权威 ...

  7. Netty学习——protoc的新手使用流程

    Netty学习——protoc的新手使用流程 关于学习的内容笔记,记下来的东西等于又过了一次脑子,记录的更深刻一些. 1. 使用IDEA创建.proto文件,软件会提示你安装相应的语法插件 安装成功之 ...

  8. Netty学习(二)使用及执行流程

    Netty简单使用 1.本文先介绍一下 server 的 demo 2.(重点是这个)根据代码跟踪一下 Netty 的一些执行流程 和 事件传递的 pipeline. 首先到官网看一下Netty Se ...

  9. netty学习资料

    netty学习资料推荐官方文档和<netty权威指南>和<netty in action>这两本书.下面收集下网上分享的资料 netty官方参考文档 Netty 4.x Use ...

随机推荐

  1. QT学习之文件系统读写类

    #QT学习之文件系统读写类 QIODevice QFileDevice QBuffer QProcess 和 QProcessEnvironment QFileDevice QFile QFileIn ...

  2. 大小端,"字节序"

    2 字节序 2.1 字节 字节(Byte)作为计算机世界的计量单位,和大家手中的人民币多少多少“元”一个意思.反正,到了计算机的世界,说字节就对了,使用人家的基本计量单位,这是入乡随俗. 比如,一个电 ...

  3. 编程思想的理解(POP,OOP,SOA,AOP)

    http://blog.csdn.net/hawksoft/article/details/7021435 1)POP--面向过程编程(Process-oriented programming ):面 ...

  4. 使用ParseExact方法将字符串转换为日期格式

    实现效果: 知识运用: DateTime结构的ParseExact方法 public static DateTime ParseExact(string s,string format,IFormat ...

  5. javascript之正则表达式基础知识小结

    javascript之正则表达式基础知识小结,对于学习正则表达式的朋友是个不错的基础入门资料.   元字符 ^ $ . * + ? = ! : | \ / ( ) [ ] { } 在使用这些符号时需要 ...

  6. require,import区别?

    遵循的模块化规范不一样 模块化规范:即为 JavaScript 提供一种模块编写.模块依赖和模块运行的方案.谁让最初的 JavaScript 是那么的裸奔呢——全局变量就是它的模块化规范. requi ...

  7. [luoguP1443]马的遍历

    首先来看一下题目描述: 题目描述 有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步 输入输出格式 输入格式: 一行四个数据,棋 ...

  8. sql server 中数据库数据导入到另一个库中

    这篇说了sql语句对于备份的数据库进行还原 ,如果数据量大了还是什么问题,发现我的数据丢失了一些,头疼 sql server 备份还原 下面使用的的数据导入来解决这个问题,因为数据量比较大,导出来的脚 ...

  9. AngularJS 一 简介以及安装环境

    AngularJS官网:https://angularjs.org AngularJS是开发动态Web应用程序的客户端JavaScript MVC框架.AngularJS最初是作为Google的一个项 ...

  10. Restframework中的Request

    1.介绍 该篇博客主要介绍restframework内置的Request类,它扩展了Django中的Request类,实现了很多方便的功能--如请求数据解析和认证等. 如: 在APIView中封装的r ...