netty的对象传输
pom
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling -->
<dependency>
<groupId>org.jboss.marshalling</groupId>
<artifactId>jboss-marshalling-serial</artifactId>
<version>2.0.0.Beta2</version>
</dependency>
处理对象的工具类 MarshallingCodeCFactory
package com.jiagoushi.lzh.网络编程.netty1.serial; import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration; /**
* Marshalling工厂
* @author(liuzhonghua)
* @since 2018-9-9
*/
public final class MarshallingCodeCFactory { /**
* 创建Jboss Marshalling解码器MarshallingDecoder
* @return MarshallingDecoder
*/
public static MarshallingDecoder buildMarshallingDecoder() {
//首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
//创建了MarshallingConfiguration对象,配置了版本号为5
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
//根据marshallerFactory和configuration创建provider
UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
//构建Netty的MarshallingDecoder对象,俩个参数分别为provider和单个消息序列化后的最大长度
MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024 * 1024 * 1);
return decoder;
} /**
* 创建Jboss Marshalling编码器MarshallingEncoder
* @return MarshallingEncoder
*/
public static MarshallingEncoder buildMarshallingEncoder() {
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
//构建Netty的MarshallingEncoder对象,MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组
MarshallingEncoder encoder = new MarshallingEncoder(provider);
return encoder;
} }
实体类
req
package com.jiagoushi.lzh.网络编程.netty1.serial; import lombok.Data; import java.io.Serializable;
@Data
public class Req implements Serializable{ private static final long SerialVersionUID = 1L; private String id ;
private String name ;
private String requestMessage ;
private byte[] attachment;
}
resp
package com.jiagoushi.lzh.网络编程.netty1.serial; import lombok.Data; import java.io.Serializable;
@Data
public class Resp implements Serializable{ private static final long serialVersionUID = 1L; private String id;
private String name;
private String responseMessage;
}
server服务端
package com.jiagoushi.lzh.网络编程.netty1.serial; 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;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; public class Server { public static void main(String[] args) throws Exception{ EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
//设置日志
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
sc.pipeline().addLast(new ServerHandler());
}
}); ChannelFuture cf = b.bind(8765).sync(); cf.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully(); }
}
服务端处理类
package com.jiagoushi.lzh.网络编程.netty1.serial; import com.jiagoushi.lzh.网络编程.utils.GzipUtils;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; import java.io.File;
import java.io.FileOutputStream; public class ServerHandler extends ChannelHandlerAdapter{ @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { } @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Req req = (Req)msg;
System.out.println("Server : " + req.getId() + ", " + req.getName() + ", " + req.getRequestMessage());
byte[] attachment = GzipUtils.ungzip(req.getAttachment()); String path = System.getProperty("user.dir") + File.separatorChar + "receive" + File.separatorChar + "00"+req.getId()+".jpg";
FileOutputStream fos = new FileOutputStream(path);
fos.write(attachment);
fos.close(); Resp resp = new Resp();
resp.setId(req.getId());
resp.setName("resp" + req.getId());
resp.setResponseMessage("响应内容" + req.getId());
ctx.writeAndFlush(resp);//.addListener(ChannelFutureListener.CLOSE);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
} }
client客户端
package com.jiagoushi.lzh.网络编程.netty1.serial; import com.jiagoushi.lzh.网络编程.utils.GzipUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.io.File;
import java.io.FileInputStream; public class Client { public static void main(String[] args) throws Exception{ EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
sc.pipeline().addLast(new ClientHandler());
}
}); ChannelFuture cf = b.connect("127.0.0.1", 8765).sync(); for(int i = 0; i < 5; i++ ){
Req req = new Req();
req.setId("" + i);
req.setName("pro" + i);
req.setRequestMessage("数据信息" + i);
String path = System.getProperty("user.dir") + File.separatorChar + "sources" + File.separatorChar + "001.jpg";
File file = new File(path);
FileInputStream in = new FileInputStream(file);
byte[] data = new byte[in.available()];
in.read(data);
in.close();
req.setAttachment(GzipUtils.gzip(data));
cf.channel().writeAndFlush(req);
} cf.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
客户端处理类
package com.jiagoushi.lzh.网络编程.netty1.serial; import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil; public class ClientHandler extends ChannelHandlerAdapter{ @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { } @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
Resp resp = (Resp)msg;
System.out.println("Client : " + resp.getId() + ", " + resp.getName() + ", " + resp.getResponseMessage());
} finally {
ReferenceCountUtil.release(msg);
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
} }
netty的对象传输的更多相关文章
- Netty4.x中文教程系列(四) 对象传输
Netty4.x中文教程系列(四) 对象传输 我们在使用netty的过程中肯定会遇到传输对象的情况,Netty4通过ObjectEncoder和ObjectDecoder来支持. 首先我们定义一个U ...
- Netty轻量级对象池实现分析
什么是对象池技术?对象池应用在哪些地方? 对象池其实就是缓存一些对象从而避免大量创建同一个类型的对象,类似线程池的概念.对象池缓存了一些已经创建好的对象,避免需要时才创建对象,同时限制了实例的个数.池 ...
- 8.Netty发送对象
1.Netty发送对象简介: Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对 ByteBuf数 据流进 ...
- [netty4][netty-transport]netty之nio传输层
[netty4][netty-transport]netty之nio传输层 nio基本处理逻辑 查看这里 Selector的处理 Selector实例构建 NioEventLoop.openSelec ...
- Tcp 数据对象传输接口对象设计
输入是一个对象inputObj,接口对象.Send(inputObj),对端接收之后解包成outputObj(与inputObj应相同),触发onPackageReceive事件 事件 public ...
- 网络编程 -- RPC实现原理 -- Netty -- 迭代版本V2 -- 对象传输
网络编程 -- RPC实现原理 -- 目录 啦啦啦 V2——Netty -- 使用序列化和反序列化在网络上传输对象:需要实现 java.io.Serializable 接口 只能传输( ByteBuf ...
- netty: 编解码之jboss marshalling, 用marshalling进行对象传输
jboss marshalling是jboss内部的一个序列化框架,速度也十分快,这里netty也提供了支持,使用十分方便. TCP在网络通讯的时候,通常在解决TCP粘包.拆包问题的时候,一般会用以下 ...
- android 对象传输及parcel机制
在开发中不少要用到Activity直接传输对象,下面我们来看看,其实跟java里面差不多 自定义对象的传递:通过intent传递自定义对象的方法有两个 第一是实现Serialization接口: ...
- 网络编程应用:基于TCP协议【实现对象传输】--练习
要求: 基于TCP协议实现,客服端向服务器发送一个对象 服务器接受并显示用户信息 ,同时返回给客户端 "数据已收到" 建一个Student类,属性:name age Student ...
随机推荐
- linux不能上网问题
第一种方法: 当linux不能上网,将网络配置成dhcp(注意:这里只能小写) onboot设置能yes 第二种方法: 第三种 window+r 快捷键 HKEY_LOCAL_MACHINE--> ...
- Codeforces1073E Segment Sum 【数位DP】
题目分析: 裸的数位DP,注意细节. #include<bits/stdc++.h> using namespace std; ; int k; ][],sz[][],cnt[][]; ] ...
- 洛谷P1038神经网络题解
题目 这个题不得不说是一道大坑题,为什么这么说呢,这题目不仅难懂,还非常适合那种被生物奥赛刷下来而来到信息奥赛的学生. 因此我们先分析一下题目的坑点. 1: 题目的图分为输入层,输出层,以及中间层. ...
- [USACO12MAR] 花盆Flowerpot
类型:二分+单调队列 传送门:>Here< 题意:给出$N$个点的坐标,要求根据$x$轴选定一段区间$[L,R]$,使得其中的点的最大与最小的$y$值之差$\geq D$.求$Min\{R ...
- 【BZOJ4325】【NOIP2015】斗地主 搜索
题目描述 就是给你一副牌,问你最少几次能出完. 详细规则见规则 \(n\leq 23\) 题解 NOIP的数据非常水,错误一大堆的程序都能AC. 因为顺子对答案的影响最大,所以先枚举顺子进行搜索. 接 ...
- Hyper-V 配置虚拟网络
Hyper-V功能异常强大,不了解的自行GG 本文介绍如何使用Hyper-V在本机建立虚拟网络,创建虚拟交换机 打开Hyper-V Manager,选择右边侧边栏的Virtual Switch Man ...
- Codeforces | CF1033D 【Divisors】
题目大意:给定\(n(1\leq n\leq500)\)个数\(a_1,a_2\cdots,a_n(1\leq a_i\leq2\cdot10^{18})\),每个数有\(3\sim5\)个因数,求\ ...
- Redhat 用代理连外网
设置 /etc/yum.conf 添加proxy=http://web-proxy.corp.xx.com:8080 /etc/yum.repos.d/rhel-source.repo 里面改成ena ...
- 【转】无法获得锁 /var/lib/dpkg/lock - open (11: 资源暂时不可用) ubuntu 安装vim 及遇到的错误处理
今天,处理完问题,闲来无事,打算在虚拟机中的Ubuntu中练习shell脚本编写. 无奈,虚拟机系统所装的只有vi,这个编辑软件对于我们来说还是比较不习惯的,所以打算安装vim.好了,闲言少叙. 安装 ...
- 20165223《JAVA程序设计》第二周学习总结
20165223 <JAVA程序设计>第二周学习总结 教材学习内容总结 第二章要点 标识符与关键字 基本数据类型 类型转换运算 输入输出数据 数组 第三章要点 运算符与表达式 语句概述 i ...