博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络编程 -- RPC实现原理 -- Netty -- 迭代版本V2 -- 对象传输
阅读量:6000 次
发布时间:2019-06-20

本文共 7053 字,大约阅读时间需要 23 分钟。

 

  啦啦啦

V2——Netty -- 使用序列化和反序列化在网络上传输对象:需要实现 java.io.Serializable 接口

 只能传输( ByteBuf, FileRegion )两种类型,因此必须将对象在发送之前进行序列化,放进ByteBuf中,客户端接收到ByteBuf时,将字节码取出,反序列化成对象。

 

  Class : Server

package lime.pri.limeNio.netty.netty02.exercise;import java.net.InetSocketAddress;import java.util.Date;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.util.CharsetUtil;import lime.pri.limeNio.netty.netty03.entity.User;public class Server {    public static void main(String[] args) throws Exception {        ServerBootstrap serverBootstrap = new ServerBootstrap();        EventLoopGroup boss = new NioEventLoopGroup();        EventLoopGroup worker = new NioEventLoopGroup();        serverBootstrap.group(boss, worker);        serverBootstrap.channel(NioServerSocketChannel.class);        serverBootstrap.childHandler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelHandlerAdapter(){ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; String request = byteBuf.toString(CharsetUtil.UTF_8); System.out.println("客户端请求数据:" + request); String response = JSON.toJSONString("请求参数不正确",SerializerFeature.WriteClassName); if("Query Date".equalsIgnoreCase(request)){ response = JSON.toJSONString("当前系统时间:" + new Date().toString(),SerializerFeature.WriteClassName); }else if("Query User".equalsIgnoreCase(request)){ response = JSON.toJSONString(new User(1,"lime",new Date()), SerializerFeature.WriteClassName); } byteBuf.clear(); byteBuf.writeBytes(response.getBytes(CharsetUtil.UTF_8)); ChannelFuture channelFuture = ctx.writeAndFlush(byteBuf); channelFuture.addListener(ChannelFutureListener.CLOSE); } }); } }); ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(9999)).sync(); channelFuture.channel().closeFuture().sync(); boss.close(); worker.close(); }}

  Class : Client

package lime.pri.limeNio.netty.netty02.exercise;import java.net.InetSocketAddress;import com.alibaba.fastjson.JSON;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.util.CharsetUtil;public class Client {    public static void main(String[] args) throws Exception {        for (int i = 0; i < 10; i++) {            new Thread() {                {                    setDaemon(false);                }                public void run() {                    try {                        client();                    } catch (Exception e) {                        e.printStackTrace();                    }                };            }.start();        }    }    private static void client() throws Exception {        Bootstrap bootstrap = new Bootstrap();        EventLoopGroup worker = new NioEventLoopGroup();        bootstrap.group(worker);        bootstrap.channel(NioSocketChannel.class);        bootstrap.handler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelHandlerAdapter() { /** * 默认只捕获网络连接异常 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println(cause); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { String request = null; switch ((int) (Math.random() * 10) % 3) { case 0: request = "Query Date"; break; case 1: request = "Query User"; break; default: request = "Query What?"; break; } ctx.writeAndFlush(Unpooled.buffer().writeBytes(request.getBytes(CharsetUtil.UTF_8))); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; System.out.println("服务端响应数据 --> " + JSON.parse(byteBuf.toString(CharsetUtil.UTF_8))); } }); } }); ChannelFuture channelFuture; channelFuture = bootstrap.connect(new InetSocketAddress(9999)).sync(); channelFuture.channel().closeFuture().sync(); worker.close(); }}

  Console : Server

客户端请求数据:Query What?客户端请求数据:Query User客户端请求数据:Query User客户端请求数据:Query Date客户端请求数据:Query Date客户端请求数据:Query What?客户端请求数据:Query Date客户端请求数据:Query Date客户端请求数据:Query User客户端请求数据:Query User

  Console : Client

服务端响应数据 --> 当前系统时间:Sat Jun 24 18:21:40 CST 2017服务端响应数据 --> 请求参数不正确服务端响应数据 --> 当前系统时间:Sat Jun 24 18:21:40 CST 2017服务端响应数据 --> 请求参数不正确服务端响应数据 --> 当前系统时间:Sat Jun 24 18:21:40 CST 2017服务端响应数据 --> 当前系统时间:Sat Jun 24 18:21:40 CST 2017服务端响应数据 --> User [id=1, name=lime, birth=Sat Jun 24 18:21:40 CST 2017]服务端响应数据 --> User [id=1, name=lime, birth=Sat Jun 24 18:21:40 CST 2017]服务端响应数据 --> User [id=1, name=lime, birth=Sat Jun 24 18:21:40 CST 2017]服务端响应数据 --> User [id=1, name=lime, birth=Sat Jun 24 18:21:40 CST 2017]

啦啦啦

转载地址:http://thbmx.baihongyu.com/

你可能感兴趣的文章
docker之docker-machine用法
查看>>
IIS 7启用static JSON文件能POST方法
查看>>
P5205 【模板】多项式开根
查看>>
微博mini for Windows Phone 8 开发那些事
查看>>
redis文章索引
查看>>
OpenSSH利用处理畸形长度密码造成的时间差,枚举系统用户(CVE-2016-6210)
查看>>
Javascript回调函数
查看>>
可能是最简单的面向对象入门教程(二)为什么要有类型
查看>>
配置Openfiler做ISCS实验
查看>>
Maven启用代理访问
查看>>
LDAP & Implementation
查看>>
hdu 4597 Play Game
查看>>
hdu 1398 Square Coins (母函数)
查看>>
twitter storm 源码走读之5 -- worker进程内部消息传递处理和数据结构分析
查看>>
CCF 201503-4 网络延时
查看>>
.net获取select控件中的文本内容
查看>>
Windows 8 Metro App开发[5]导航栏(AppBar)的使用
查看>>
Effective Java -- 使可变性最小化
查看>>
开发环境中Docker的使用
查看>>
Redis 分布式锁
查看>>