netty传输java bean对象
在上一篇博客(netty入门实现简单的echo程序)中,我们知道了如何使用netty发送一个简单的消息,但是这远远是不够的。在这篇博客中,我们来使用netty发送一个java bean对象的消息,但是要发送对象类型的消息,必然要将java对象进行序列化,在java中序列化框架有很多中,此处我们使用protostuff来进行序列化,不了解protostuff的可以先看一下这篇博客(protostuff序列化)了解一下简单的用法。
需求:
客户端在连接上服务器端时,向服务器发送100个Person对象。
服务器端接收到消息后在控制台上打印即可。
消息发送的协议:4个字节的长度(长度是后面对象的长度,不包含自身的4个字节),后面是实际的要发送的数据
实现思路:
一、服务器端:
1、服务器端先用LengthFieldBasedFrameDecoder进行解码,获取到一个完整的ByteBuf消息
2、然后编写ProtostuffDecoder解码器将上一步解码出来的消息,转换成一个Person对象
3、编写ProtoStuffServerHandler类用于将上一步解码出来的Person对象输出出来
二、客户端
1、编写ProtostuffClientHandler类用于向服务器端发送Person对象
2、编写ProtostuffEncoder来进行将Person对象转换成字节数组
3、借助netty的LengthFieldPrepender来向上一步的字节数组前增加4个字节的消息长度
半包的处理主要是借助netty提交的LengthFieldBasedFrameDecoder来进行处理
注意:
new LengthFieldPrepender(4) ==> 会在发送的数据前增加4个字节表示消息的长度
new LengthFieldBasedFrameDecoder(10240, 0, 4, 0, 4) ==> 10240表示如果此次读取的字节长度比这个大说明可能是别人伪造socket攻击,将会抛出异常,第一个4表示读取四个字节表示此次 消息的长度,后面一个4表示丢弃四个字节,然后读取业务数据。
实现步骤:
一、引入maven依赖
<strong><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.huan.netty</groupId>
<artifactId>netty-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>netty-study</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-api</artifactId>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-bom</artifactId>
<version>1.4.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
</strong>
二、编写实体类Person(客户端将会发送这个对象,服务器端接收这个对象)
<strong>@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private int id;
private String name;
}</strong>
三、编写ProtostuffDecoder用将ByteBuf中的数据转换成Person对象
<strong>public class ProtostuffDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Schema<Person> schema = RuntimeSchema.getSchema(Person.class);
Person person = schema.newMessage();
byte[] array = new byte[in.readableBytes()];
in.readBytes(array);
ProtobufIOUtil.mergeFrom(array, person, schema);
out.add(person);
}
}</strong>
四、编写ProtoStuffServerHandler用于将接收到的数据输出到控制台
<strong>@Slf4j
public class ProtoStuffServerHandler extends ChannelInboundHandlerAdapter {
private int counter = 0;
/**
* 接收到数据的时候调用
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Person person = (Person) msg;
log.info("当前是第[{}]次获取到客户端发送过来的person对象[{}].", ++counter, person);
}
/** 当发生了异常时,次方法调用 */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("error:", cause);
ctx.close();
}
}
</strong>
五、编写netty的服务端,用于启动netty的服务
<strong>@Slf4j
public class NettyServer {
public static void main(String[] args) throws Exception {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker)//
.channel(NioServerSocketChannel.class)// 对应的是ServerSocketChannel类
.option(ChannelOption.SO_BACKLOG, 128)//
.handler(new LoggingHandler(LogLevel.TRACE))//
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(10240, 0, 4, 0, 4));
ch.pipeline().addLast(new ProtostuffDecoder());
ch.pipeline().addLast(new ProtoStuffServerHandler());
}
});
ChannelFuture future = bootstrap.bind(9090).sync();
log.info("server start in port:[{}]", 9090);
future.channel().closeFuture().sync();
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}</strong>
此处需要注意解码器的顺序:
必须要先是LengthFieldBasedFrameDecoder,然后是ProtostuffDecoder,在是ProtoStuffServerHandler
六、编写客户端的handler处理器,用于向服务器端发送Person对象
<strong>@Slf4j
public class ProtostuffClientHandler extends ChannelInboundHandlerAdapter {
/**
* 客户端和服务器端TCP链路建立成功后,此方法被调用
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Person person;
for (int i = 0; i < 100; i++) {
person = new Person();
person.setId(i);
person.setName("张三" + i);
ctx.writeAndFlush(person);
}
}
/**
* 发生异常时调用
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("client error:", cause);
ctx.close();
}
}</strong>
七、编写ProtostuffEncoder编码器,用于将Person对象编码成字节数组
<strong>public class ProtostuffEncoder extends MessageToByteEncoder<Person> {
@Override
protected void encode(ChannelHandlerContext ctx, Person msg, ByteBuf out) throws Exception {
LinkedBuffer buffer = LinkedBuffer.allocate(1024);
Schema<Person> schema = RuntimeSchema.getSchema(Person.class);
byte[] array = ProtobufIOUtil.toByteArray(msg, schema, buffer);
out.writeBytes(array);
}
}</strong>
八、编写客户端
<strong>@Slf4j
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)//
.channel(NioSocketChannel.class)//
.option(ChannelOption.TCP_NODELAY, true)//
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new ProtostuffEncoder());
ch.pipeline().addLast(new ProtostuffClientHandler());
}
});
ChannelFuture future = bootstrap.connect("127.0.0.1", 9090).sync();
log.info("client connect server.");
future.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
</strong>
注意:此处也需要注意initChannel方法中的编码器加入的顺序
ProtostuffEncoder->将Person对象转换成字节数组
LengthFieldPrepender->在上一步的字节数组前加入4个字节的长度
九、启动服务器端和客户端进行测试
netty传输java bean对象的更多相关文章
- spring mvc返回json字符串数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable
1.spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable 2. @RequestMapping(val ...
- mongodb中Gson和java##Bean对象转化类
此类使用感觉比较繁琐, 每个字段加注解才可以使用, 不如mongoTemplate使用方便, 但如果使用mongo客户端的话, 还是比手动拼接快一点, 所以贴在这儿 package com.iwher ...
- java bean对象拷贝
Java的bean的属性复制,大家可以都看一下. 谈谈Java开发中的对象拷贝http://www.wtnull.com/view/2/e6a7a8818da742758bcd8b73d49d6be2 ...
- 合并两个java bean对象非空属性(泛型)
import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; cl ...
- json与java bean对象转换
第一步:引入fastjson的依赖jar包 注:如果引入此版本的依赖,导致项目不能启动(报错:找不到启动类);那么可以换一个版本的fastjson即可. 给出文字版: <!-- fastjson ...
- java 从spring容器中获取注入的bean对象
java 从spring容器中获取注入的bean对象 CreateTime--2018年6月1日10点22分 Author:Marydon 1.使用场景 控制层调用业务层时,控制层需要拿到业务层在 ...
- Java进阶知识17 Spring Bean对象的创建细节和创建方式
本文知识点(目录): 1.创建细节 1) 对象创建: 单例/多例 2) 什么时候创建? 3)是否延迟创建(懒加载) 4) 创建对象之后, ...
- java用Annotation注入到成员Bean对象
java用Annotation注入到成员Bean对象 在使用一些java框架的时候,经常看到一些注解,而且使用注解之后就可以免去一些xml的繁琐配置,本文记录如何通过注解获得成员Bean对象. 一.首 ...
- Java JSON、XML文件/字符串与Bean对象互转解析
前言 在做web或者其他项目中,JSON与XML格式的数据是大家经常会碰见的2种.在与各种平台做数据对接的时候,JSON与XML格式也是基本的数据传递格式,本文主要简单的介绍JSON/XML ...
随机推荐
- Lambda表达式——注重过程的编程思想
一.使用匿名内部类的匿名对象创建线程和Lambda表达式写法 Lambda表达式写法不用去定义一个Runable接口的实现类: 二.方法入参是一个接口或者接口的实现类 三.对某个类的一些对象实例进行排 ...
- AI异构通信:重压下的突围,华为P50系列的卓越体验
撰文 |懂懂 编辑 | 秦言 来源:懂懂笔记 "华为不会让消费者失望."华为消费者业务CEO余承东在P50系列发布会上如是说. 今年4月美国对华为第四轮制裁以来,华为终端产品无缘5 ...
- MySQL索引、事务、存储引擎
一.MySQL 索引 1.索引的概念 ●索引是一个排序的列表,在这个列表中存储着索引的值和包含这个值的数据所在行的物理地址(类似于C语言的链表通过指针指向数据记录的内存地址).●使用索引后可以不用扫描 ...
- Fastjson反序列化漏洞基础
Fastjson反序列化漏洞基础 FastJson是alibaba的一款开源JSON解析库,可用于将Java对象转换为其JSON表示形式,也可以用于将JSON字符串转换为等效的Java对象. 0x0 ...
- EditPlus配置C/C++运行环境
1.安装MinGW和EditPlus 2.打开EditPlus ctrl+1 编译 ctrl+2 运行
- C++打字小游戏
从@小蔡编程 那里获得的灵感,原文地址:https://www.cnblogs.com/xiaocaibiancheng/p/15158997.html 那篇文章是说python写打字游戏的,本文就用 ...
- css3 flex的IE8浏览器兼容问题
我这是进行判断浏览器 css判断ie版本才引用样式或css文件 <!--[if !IE]><!--> 除IE外都可识别 <!--<![endif]--> &l ...
- Java面向对象系列(3)- 回顾方法的调用
方法的调用 静态方法 非静态方法 形参和实参 值传递和引用传递 this关键字(继承篇讲解) 静态方法 非静态方法 形参和实参 package oop.demo01; public class Dem ...
- 使用uView UI+UniApp开发微信小程序--微信授权绑定和一键登录系统
在前面随笔<使用uView UI+UniApp开发微信小程序>和<使用uView UI+UniApp开发微信小程序--判断用户是否登录并跳转>介绍了微信小程序的常规登录处理和验 ...
- django 使用装饰器验证用户登陆
使用装饰器验证用户登陆,需要使用@method_decorator 首先需引用,method_decorator,并定义一个闭包 from django.utils.decorators import ...