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

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

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

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

下面贴上全部代码

UserInfo.java

package MessagePack;

import org.msgpack.annotation.Message;

@Message
public class UserInfo
{
private int age; private String name; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString()
{
return "age = " + age + "; name = " + name;
}
}

MsgpackDecoder.java

package MessagePack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack; import java.util.List; public class MsgpackDecoder extends MessageToMessageDecoder<ByteBuf>
{
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception
{
final byte[] array;
final int length = byteBuf.readableBytes();
array = new byte[length];
byteBuf.getBytes(byteBuf.readerIndex(), array, 0, length);
MessagePack msgpack = new MessagePack();
list.add(msgpack.read(array));
}
}

MsgpackEncoder.java

package MessagePack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack; public class MsgpackEncoder extends MessageToByteEncoder<Object>
{
protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception
{
MessagePack msgpack = new MessagePack();
byte[] raw = msgpack.write(o);
byteBuf.writeBytes(raw);
}
}

EchoServer.java

package MessagePack;

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; public class EchoServer
{
private final int port; public EchoServer(int port)
{
this.port = port;
} public void bind() throws Exception
{
//配置服务端的NIO线程
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
//.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>()
{
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception
{
socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
socketChannel.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
socketChannel.pipeline().addLast(new EchoServerHandler());
}
});
//绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync(); //等待服务端监听端口关闭
System.out.println("bind");
f.channel().closeFuture().sync();
System.out.println("close");
}
finally
{
//优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception
{
int port = 22233;
if (null != args && args.length > 0)
{
try
{
port = Integer.parseInt(args[0]);
}
catch (Exception e)
{
port = 22233;
}
} new EchoServer(port).bind();
}
}

EchoServerHandler.java

package MessagePack;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class EchoServerHandler extends ChannelHandlerAdapter
{
@Override
public void channelActive(ChannelHandlerContext ctx)
{
System.out.println("channelActive");
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
System.out.println("Server receive the mspack message : " + msg);
ctx.writeAndFlush(msg);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
{
System.out.println(cause.getMessage());
ctx.close();
}
}

EchoClient.java

package MessagePack;

import io.netty.bootstrap.Bootstrap;
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; public class EchoClient
{
private final String host;
private final int port;
private final int sendNumber; public EchoClient(String host, int port, int sendNumber)
{
this.host = host;
this.port = port;
this.sendNumber = sendNumber;
} public void connect() throws Exception
{
//配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try
{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>()
{
protected void initChannel(SocketChannel socketChannel) throws Exception
{
socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
socketChannel.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
socketChannel.pipeline().addLast(new EchoClientHandler(sendNumber));
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync(); System.out.println("connect");
//等待客户端链路关闭
f.channel().closeFuture().sync();
System.out.println("close");
}
finally
{
//优雅退出,释放NIO线程组
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception
{
int port = 22233;
if (null != args && args.length > 0)
{
try
{
port = Integer.parseInt(args[0]);
}
catch (Exception e)
{
port = 22233;
}
} new EchoClient("127.0.0.1", 22233, 100).connect();
}
}

EchoClientHandler.java

package MessagePack;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class EchoClientHandler extends ChannelHandlerAdapter
{
private final int sendNumber; public EchoClientHandler(int sendNumber)
{
this.sendNumber = sendNumber;
} @Override
public void channelActive(ChannelHandlerContext ctx)
{
System.out.println("channelActive");
// ByteBuf byteBuf = Unpooled.copiedBuffer("asdf".getBytes());
// ctx.writeAndFlush(byteBuf); UserInfo[] infos = UserInfo();
for (UserInfo infoE : infos)
{
ctx.write(infoE);
}
ctx.flush();
} private UserInfo[] UserInfo()
{
UserInfo[] userInfos = new UserInfo[sendNumber];
UserInfo userInfo = null;
for (int i=0; i < sendNumber; i++)
{
userInfo = new UserInfo();
userInfo.setAge(i);
userInfo.setName("ABCDEFG --->" + i);
userInfos[i] = userInfo;
}
return userInfos;
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
System.out.println("Client receive the msgpack message : " + msg);
//ctx.write(msg);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
{
ctx.flush();
}
}

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. typescript 添加基础类型的扩展方法

    以时间转换为案例: //声明接口,也是在声明date这个基础类型要定义一个format的扩展方法,不写接口声明会报错 interface Date { Format(fmt:string):strin ...

  2. Android(java)学习笔记19:Java中InetAddress类概述和使用

    1. 要想让网络中的计算机能够互相通信,必须为每台计算机指定一个标识号,通过这个标识号来指定要接受数据的计算机和识别发送的计算机. 在TCP/IP协议中,这个标识号就是IP地址. 那么,我们如果获取和 ...

  3. 【转】netstat 命令当中的内部地址和外部地址分别代表的是什么?

    RT,用自己的话解释,不要搬网上的内容.尽量可以简洁,谢谢 2015-03-07 17:41 提问者采纳   网络连接是有2方参与,自己就是“内部地址”,别人就是“外部地址”,就这么简洁. 再举个例子 ...

  4. activeMQ消息队列的使用

    ActiveMQ解决问题:  1.解决服务之间的耦合 2.增加系统并发处理量. 它使用的是标准生产者和消费者模型.有两种数据结构:Queue/Topic 1.Queue队列,生产者生产一个消息,只能由 ...

  5. Spring管理连接池的几种方式

    第一种方式:.Spring常规的数据库连接方法: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations=&qu ...

  6. 【转】学习jar命令 创建和解压jar文件包

    java编程中每天都用不少jar文件,项目开发中不停地导包,在忙完了一天的工作,放下那些复杂的业务实现,不仅想问这些jar包怎么生成的,jar包有哪些独特的地方等等. 原来这些经常见到的jar包是ja ...

  7. 解决 Database Configuration Assistannt安装oracle实例使的 警告

    在创建到85%的时候报错,错误如下: 解决办法: 经过查看警告中给出的日志文件F:\develop\oracle_data\app\Administrator\cfgtoollogs\dbca\tes ...

  8. 【luogu P2947 [USACO09MAR]向右看齐Look Up】 题解

    题目链接:https://www.luogu.org/problemnew/show/P2947 因为在单调队列上被dalao们锤爆 怒刷单调队列题 何为单调队列? 设我们的队列为从左至右单调递增 对 ...

  9. 深入 Struts2 的配置 - 处理多个请求-处理请求结果-模型驱动-异常机制

    转:http://www.java3z.com/cwbwebhome/article/article2/2938.html?id=1631 本部分主要介绍struts.xml的常用配置. 1.1.   ...

  10. GPU卡掉卡

    这几天用GPU卡跑东西,老是提示opencv的一个问题.但是我换个数据跑就没问题.说明代码是没问题的.发挥我作为女人的特质,从起试试吧.结果从起后找不到GPU卡了.nvidia-smi提示我没有安装最 ...