package object.server.impl;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder; public class SubReqServer {
public void start(int port) {
NioEventLoopGroup workGroup = new NioEventLoopGroup();
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workGroup);
bootstrap.channel(NioServerSocketChannel.class);
// 配置 NioServerSocketChannel 的 tcp 参数, BACKLOG 的大小
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
/*
* 使用 weakCachingConcurrentResolver 创建线程安全的 WeakReferenceMap
* ,对类加载器进行缓存
* ,它支持多线程并发访问,当虚拟机内存不足时,会释放缓存中的内存,防止内存泄露,为了房子异常码流和解码错位导致的内存溢出
* ,这里将当个对象序列化之后的字节数组长度设置为1M
*/
ObjectDecoder objectDecoder = new ObjectDecoder(1024 * 1024,
ClassResolvers.weakCachingConcurrentResolver(this
.getClass().getClassLoader())); ch.pipeline().addLast(objectDecoder);
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast(new SubReqHandler());
}
});
// 绑定端口,随后调用它的同步阻塞方法 sync 等等绑定操作成功,完成之后 Netty 会返回一个 ChannelFuture
// 它的功能类似于的 Future,主要用于异步操作的通知回调.
ChannelFuture channelFuture;
try {
channelFuture = bootstrap.bind(port).sync();
// 等待服务端监听端口关闭,调用 sync 方法进行阻塞,等待服务端链路关闭之后 main 函数才退出.
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
} public static void main(String[] args) {
SubReqServer server = new SubReqServer();
server.start(9091);
}
}
package object.server.impl;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class SubReqHandler extends ChannelHandlerAdapter { @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
super.exceptionCaught(ctx, cause);
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception { System.out.println(msg);
SubscriptResp sub = new SubscriptResp();
ctx.writeAndFlush(sub);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} }

Client

package object.client.impl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder; public class SubReqClient {
public void connect(String host, int port) {
NioEventLoopGroup workGroup = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
/*
* 禁止堆类加载器进行缓存,他在基于 OSGI 的动态模块化编程中经常使用,由于 OSGI 可以进行热部署和热升级,当某个
* bundle
* 升级后,它对应的类加载器也将一起升级,因此在动态模块化的编程过程中,很少对类加载器进行缓存,因为他随时可能会发生变化.
*/
ch.pipeline().addLast(
new ObjectDecoder(1024 >> 2, ClassResolvers
.cacheDisabled(getClass().getClassLoader())));
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast(new SubReqClientHandler());
}
}); // 发起异步链接操作
ChannelFuture future;
try {
future = bootstrap.connect(host, port).sync();
// 等待客户端链路关闭
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workGroup.shutdownGracefully();
}
} public static void main(String[] args) {
new SubReqClient().connect("localhost", 9091);
}
}

ClientHandler

package object.client.impl;

import object.server.impl.SubScriptReq;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class SubReqClientHandler extends ChannelHandlerAdapter { @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
SubScriptReq req = new SubScriptReq();
req.setSubReq(999);
ctx.writeAndFlush(req);
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println(msg);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} }

POJO

package object.server.impl;

import java.io.Serializable;

public class SubscriptResp implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4923081103118853877L;
private Integer subScriptID;
private String respCode;
private String desc; public Integer getSubScriptID() {
return subScriptID;
} public void setSubScriptID(Integer subScriptID) {
this.subScriptID = subScriptID;
} public String getRespCode() {
return respCode;
} public void setRespCode(String respCode) {
this.respCode = respCode;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} @Override
public String toString() {
return "SubscriptResp [subScriptID=" + subScriptID + ", respCode="
+ respCode + ", desc=" + desc + "]";
} }

req

package object.server.impl;

import java.io.Serializable;

public class SubScriptReq implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4686274228090335845L;
private Integer subReq;
private String userName;
private String productName;
private String address; public Integer getSubReq() {
return subReq;
} public void setSubReq(Integer subReq) {
this.subReq = subReq;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getProductName() {
return productName;
} public void setProductName(String productName) {
this.productName = productName;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} @Override
public String toString() {
return "SubScriptReq [subReq=" + subReq + ", userName=" + userName
+ ", productName=" + productName + ", address=" + address + "]";
} }

netty 对象序列化传输示例的更多相关文章

  1. Netty5+Jboss(Marshalling)完成对象序列化传输

    TCP在网络通讯的时候,通常在解决TCP粘包.拆包问题的时候,一般会用以下几种方式: 1. 消息定长 例如每个报文的大小固定为200个字节,如果不够,空位补空格: 2. 在消息尾部添加特殊字符进行分割 ...

  2. netty: marshalling传递对象,传输附件GzipUtils

    netty: marshalling传递对象,传输附件GzipUtils 前端与服务端传输文件时,需要双方需要进行解压缩,也就是Java序列化.可以使用java进行对象序列化,netty去传输,但ja ...

  3. java 对象序列化 RMI

    对于一个存在于Java虚拟机中的对象来说,其内部的状态只保持在内存中.JVM停止之后,这些状态就丢失了.在很多情况下,对象的内部状态是需要被持久化下来的.提到持久化,最直接的做法是保存到文件系统或是数 ...

  4. Java对象序列化与RMI

    对于一个存在于Java虚拟机中的对象来说,其内部的状态只保持在内存中.JVM停止之后,这些状态就丢失了.在很多情况下,对象的内部状态是需要被持久化下来的.提到持久化,最直接的做法是保存到文件系统或是数 ...

  5. Java对象序列化剖析

    对象序列化的目的 1)希望将Java对象持久化在文件中 2)将Java对象用于网络传输 实现方式 如果希望一个类的对象可以被序列化/反序列化,那该类必须实现java.io.Serializable接口 ...

  6. C#对象序列化与反序列化zz

      C#对象序列化与反序列化(转载自:http://www.cnblogs.com/LiZhiW/p/3622365.html) 1. 对象序列化的介绍........................ ...

  7. C#对象序列化与反序列化

    C#对象序列化与反序列化(转载自:http://www.cnblogs.com/LiZhiW/p/3622365.html) 1. 对象序列化的介绍.......................... ...

  8. C#[Serializable]在C#中的作用-NET 中的对象序列化

    为什么要使用序列化?最重要的两个原因是:将对象的状态保存在存储媒体中以便可以在以后重新创建出完全相同的副本:按值将对象从一个应用程序域发送至另一个应用程序域.例如,序列化可用于在 ASP.NET 中保 ...

  9. [转载]C#对象序列化与反序列化

    文章写的实在是太好了,忍不住转来: http://www.cnblogs.com/LiZhiW/p/3622365.html#_Toc8478 1.对象序列化的介绍 (1).NET支持对象序列化的几种 ...

随机推荐

  1. java里的基本数据类型和引用数据类型

    一.基本数据类型: byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围-32768 ...

  2. yii2过滤器(filter)

    一.VerbFilter VerbFilter检查请求动作的HTTP请求方式是否允许执行, 如果不允许,会抛出HTTP 异常 use yii\filters\VerbFilter; public fu ...

  3. list utilities监视数据库前滚操作

    您可以使用 db2pd 或 LIST UTILITIES 命令来监视数据库前滚操作的进度. 过程 发出 LIST UTILITIES 命令并指定 SHOW DETAIL 参数 db2 LIST UTI ...

  4. Sublime_正则查找替换

    在sublime编辑器中使用正则表达式对内容进行查找和替换: (1)Find——Replace... (2)出现下图界面 注意:点击左边第一个按钮,开启正则表达式功能. (3) (4)点击Replac ...

  5. J - 青蛙的约会(扩展欧几里得)

    https://vjudge.net/contest/218366#problem/J 第一步追及公式要写对:y+nk-(x+mk)=pL => (n-m)k+lp=x-y 可以看出扩展欧几里得 ...

  6. django之setting配置汇总

    前面的随笔中我们经常会改setting配置也经常将一些配置混淆今天主要是将一些常见的配置做一个汇总. setting配置汇总 1.app路径 INSTALLED_APPS = [ 'django.co ...

  7. C#异步Task编程模型实战手册

    一.课程介绍 本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的第一部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高级编程的技巧分享出来给大家进行学习,不断的收集.整理 ...

  8. 如何将Powerdesign物理模型中的name复制成comment

    Option Explicit ValidationMode = True InteractiveMode = im_Batch Dim mdl ' the current model ' get t ...

  9. PDF.js 分片下载的介绍2:分片下载demo

    上一个章节,简要说了以下分片下载的几个特性.今天主要用示例说明一下pdf.js分片下载. 服务器环境: php7.2 nginx 1.14 ubuntu 18.04测试浏览器:谷歌浏览器 70.0.3 ...

  10. 使用Nodpad++正则替换

    例如有以下格式数据: 现在需要将每一行的10位长度的数字串后面增加等号“=”