Netty入门
一、 为什么要异步
思考
-
医生看病场景
上述并不是异步的
下面看看Netty是怎么做的
1)首先对任务进行划分
2)理解netty工作原理(提升的不是响应时间,提升的是吞吐量)吞吐量: 单位时间处理请求的速率
二、Netty黏包半包问题
1、问题复现
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.87.Final</version>
</dependency>
黏包复现
client:
1.代码:
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import java.nio.ByteBuffer;
/**
* @version 1.0
* @ClassName HelloworldClient
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldClient {
public static void main(String[] args) {
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.group(worker);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
//会在连接channel建立成功时后,触发active事件
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 10; i++) {
ByteBuf buffer = ctx.alloc().buffer(12);
buffer.writeBytes("hello,world!".getBytes());
ctx.writeAndFlush(buffer);
}
}
});
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
log.error("client error: {}",e);
} finally {
worker.shutdownGracefully();
}
}
}
server:
package cn.com.agree.netty.demo.sthalfpackage;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
/**
* @version 1.0
* @ClassName HelloWorldServer
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldServer {
public static void main(String[] args) {
new HelloWorldServer().start();
}
public void start(){
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.channel(NioServerSocketChannel.class);
//serverBootstrap.option(ChannelOption.SO_RCVBUF,10);
serverBootstrap.group(boss,worker);
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
log.error("server error",e);
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
2.结果分析
原因一:业务上,接收方的ByteBuf设置过大(Netty默认1024字节),发送方向接收方发送多条数据,如果数据较小,此时就会出现黏包现象。
原因二:传输层中,TCP采用滑动窗口来进行传输控制,接收方会告诉发送方在某一时刻能发送多少数据(窗口尺寸),当滑动窗口为0时,一般情况下(两种特殊情况这里不做考虑)不能发送数据。实质上就是通过缓冲区达到流量控制的目的。如果滑动窗口远大于发送数据的大小,且接收方有没有及时处理,则缓冲区内就有多个报文,从而产生黏包现象。
原因三:TCP段和IP数据报对会给报文添加首部,如果业务报文较小,首部比业务报文大,此时发送数据会造成流量浪费,因此Nagle算法尽可能多地攒够报文再发送,从而产生黏包现象。
半包复现
// 调整服务器端 滑动窗口大小,一般不用设置,在建立连接后系统自动设置,netty默认的是1024
serverBootstrap.option(ChannelOption.SO_RCVBUF, 10);
// 调整客户端 滑动窗口大小,一般不用设置,在建立连接后系统自动设置,netty默认的是1024
bootstrap.option(ChannelOption.SO_SNDBUF, 10);
// 调整 netty 的接收缓冲区大小(ByteBuf) AdaptiveRecvByteBufAllocator(最小值, 初始值, 最大值)
serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16));
1.代码
在上述server 代码加上
serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(10, 10, 10));
2.结果分析
2、解决方案
方案列举:
短链接:发一个包建立一次连接,这样连接建立到连接断开之间就是消息的边界,缺点效率太低
定长解码器:每一条消息采用固定长度,缺点浪费空间
行解码器:每一条消息采用分隔符,例如 \n,缺点需要转义
LTC解码器:每一条消息分为 head 和 body,head 中包含 body 的长度
①短链接(连接、停止作为边界)
tcp之所以有黏包、半包是因为消息没有边界,那么短链接这种方式可以人为的让消息从连接、建立、断开作为消息边界。
思路:原本一个连接发送10条数据,更改为建立10次连接,每次连接发送一条数据。
若是不进行自己控制窗口的大小,默认接收端与发送端也会进行窗口大小的协商,来进行自适应一个窗口大小。现在操作系统也比较智能,能够自行的进行调整。
优缺点:效率低,虽然能够解决黏包问题,但是还是不能够避免半包问题。其消息边界就是连接-建立-结束。
代码:
使用客户端发送16字节的数据举例
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import java.nio.ByteBuffer;
/**
* @version 1.0
* @ClassName HelloworldClient
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldClient {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
send();
}
}
private static void send() {
NioEventLoopGroup worker = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.group(worker);
Channel channel = null;
try {
channel = bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// ch.pipeline().addLast(new StringEncoder());//String=>ByteBuf
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
//会在连接channel建立成功时后,触发active事件
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buffer = ctx.alloc().buffer(16);
buffer.writeBytes("hello,world!hell".getBytes());
ctx.writeAndFlush(buffer);
ctx.channel().close();
worker.shutdownGracefully();
log.debug("finish!");
}
});
}
}).connect("127.0.0.1", 8282).sync().channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("客户端连接成功:{}", bootstrap);
channel.closeFuture().addListener(future -> {
worker.shutdownGracefully();
});
}
}
server端
//设置ByteBuf缓冲区为16字节(调整netty的接收缓冲区后(小于客户端一次发送的大小):那么也会出现半包情况,但所幸数据是不会丢的。
serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new
AdaptiveRecvByteBufAllocator(16, 16, 16));
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
/**
* @version 1.0
* @ClassName HelloWorldServer
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldServer {
public static void main(String[] args) {
new HelloWorldServer().start();
}
public void start(){
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
//设置ByteBuf缓冲区为16字节(调整netty的接收缓冲区后(小于客户端一次发送的大小):那么也会出现半包情况,但所幸数据是不会丢的。
serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16));
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.group(boss,worker);
serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8282).sync();
log.info("服务器启动成功!");
//channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
log.error("server error",e);
} finally {
// boss.shutdownGracefully();
// worker.shutdownGracefully();
}
}
}
结果:
②定长解码器(指定字节长度解码)
Netty中提供了一个FixedLengthFrameDecoder(固定长度解析器),是一个特殊的handler,只不过是专门用来进行解码的。
思路:客户端给每个发送的数据封装成定长的长度(多余的使用分隔符,统一规定)最后统一通过一个ByteBuf发送出去;服务端的话通过使用FixedLengthFrameDecoder来进行固定长度解析,那么每次自然也就解析到定长的Bytebuf来进行处理。
方案:服务器与客户端作一个长度约定,服务端只有收到固定长度的才会接收完毕,否则也会进行等待直到够一定长度才向下一个handler传递;若是一次接收到的长度过大,ByteBuf也只会截取固定长度的内容并对下一个handler进行传递,多出来的部分会留着后序发来的数据再进行组合。
优缺点:虽然能够解决黏包、半包问题,但是客户端要构成定长长度有时候无效内容占用的字节数比较多(若是传递的内容比较少,则为了构成定长长度那么就会产生资源浪费)。
代码
客户端
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Random;
* @version 1.0
* @ClassName HelloWorldClient02
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
@Slf4j
public class HelloWorldClient02 {
public static void main(String[] args) throws InterruptedException {
send();
}
private static void send() throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
Channel channel = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buffer = ctx.alloc().buffer();
char c = '0';
final Random r = new Random();
//生成10个定长的字节数组全部写入到一个ByteBuf中,最后发送出去
//目的:检验服务器能否每次取到定长ByteBuf
for (int i = 0; i < 10; i++) {
final byte[] bytes = fill10Bytes(c, r.nextInt(10) + 1);
buffer.writeBytes(bytes);
c++;
}
ctx.channel().writeAndFlush(buffer);
}
});
}
}).connect("127.0.0.1", 8282).sync().channel();
log.debug("客户端连接成功:{}", channel);
channel.closeFuture().addListener(future -> {
group.shutdownGracefully();
});
}
/**
* 生成len个指定c字符,定长为10,多余部分使用"_"填充
* @param c 填充字符
* @param len 字符长度
* @return 填充好的字节数组
*/
public static byte[] fill10Bytes(char c, int len){
final byte[] bytes = new byte[10];
Arrays.fill(bytes, (byte) '_');
for (int i = 0; i < len; i++) {
bytes[i] = (byte) c;
}
System.out.println(new String(bytes));
return bytes;
}
}
服务端
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
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.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
/**
* @version 1.0
* @ClassName HelloWorldServer
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldServer02 {
public static void main(String[] args) {
new HelloWorldServer02().start();
}
public void start(){
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.group(boss,worker);
serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
//使用定长解码器:固定设置为10个字节,也就是每次读事件都会拿到10个字节长度的ByteBuf
ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8282).sync();
log.info("服务器启动成功!");
//channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
log.error("server error",e);
} finally {
// boss.shutdownGracefully();
// worker.shutdownGracefully();
}
}
}
结果:
③行解码器(分割符解决)
行解码器(分隔符解决)使用分隔符来作为消息的边界。
在Netty中提供了两个解码器:
LineBasedFrameDecoder:指定以换行符作为分隔符。\n或者\r\n,使用它的时候,会有一个最大长度限制,若是超过了字长长度还没有找到换行符就会抛出一个异常
DelimiterBasedFrameDecoder:可以自定义符号来作为分隔符,在构造方法中有最大长度何一个Bytebuf类型的分隔符.
缺点:效率比较低,需要一个一个字节去找消息的边界!
1)测试"_"分隔符
代码:
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Random;
/**
* @version 1.0
* @ClassName HelloworldClient
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldClient03 {
public static void main(String[] args) {
send();
}
private static void send() {
NioEventLoopGroup worker = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.group(worker);
Channel channel = null;
try {
channel = bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// ch.pipeline().addLast(new StringEncoder());//String=>ByteBuf
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
//会在连接channel建立成功时后,触发active事件
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//测试二:DelimiterBasedFrameDecoder
testDelimiterBasedFrameDecoder();
}
});
}
}).connect("127.0.0.1", 8282).sync().channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("客户端连接成功:{}", bootstrap);
channel.closeFuture().addListener(future -> {
worker.shutdownGracefully();
});
}
/**
* 测试DelimiterBasedFrameDecoder界定符解码器:可自定义界定符(界定符为ByteBuf类型传入)
*/
public static void testDelimiterBasedFrameDecoder(){
char delimiter = '_';
final ByteBuf buffer = getByteBufByDelimiter(delimiter);
final ByteBuf delimiterByteBuf = ByteBufAllocator.DEFAULT.buffer().writeByte(delimiter);
// DelimiterBasedFrameDecoder:参数一为检测的最大长度(若是超过最大长度还检测不到指定界定符直接抛异常),参数二为界定符
final EmbeddedChannel channel = new EmbeddedChannel(new DelimiterBasedFrameDecoder(11, delimiterByteBuf), new LoggingHandler());
// 模拟入站操作
channel.writeInbound(buffer);
}
private static ByteBuf getByteBufByDelimiter(char delimiter) {
final ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
log.debug("buffer:{}",buffer.capacity());
Random r = new Random();
char c = 'a';
for (int i = 0; i < 10; i++) {
buffer.writeBytes(makeRandomBytes(r, c, delimiter));
c++;
}
return buffer;
}
/**
* 构造随机长度的字节数组末尾添加分隔符"\n"作为区分
* @param r
* @param c 随机字符
* @param delimiter 界定符
* @return
*/
public static byte[] makeRandomBytes(Random r, char c, char delimiter){
final int num = r.nextInt(10) + 1;
final byte[] data = new byte[num + 1];
//填充[0, num)区间
Arrays.fill(data, 0, num, (byte) c);
data[num] = (byte) delimiter;
System.out.println(new String(data));
return data;
}
}
结果:
2)测试"\n"分隔符
代码:
package cn.com.agree.netty.demo.sthalfpackage;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Random;
/**
* @version 1.0
* @ClassName HelloworldClient
* @Description TODO 类描述
* @date 2024/4/22 4:55 下午
**/
@Slf4j
public class HelloWorldClient03 {
public static void main(String[] args) {
send();
}
private static void send() {
NioEventLoopGroup worker = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.group(worker);
Channel channel = null;
try {
channel = bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// ch.pipeline().addLast(new StringEncoder());//String=>ByteBuf
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
//会在连接channel建立成功时后,触发active事件
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//测试一:LineBasedFrameDecoder
testLineBasedFrameDecoder();
//测试二:DelimiterBasedFrameDecoder
// testDelimiterBasedFrameDecoder();
}
});
}
}).connect("127.0.0.1", 8282).sync().channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("客户端连接成功:{}", bootstrap);
channel.closeFuture().addListener(future -> {
worker.shutdownGracefully();
});
}
/**
* 测试LineBasedFrameDecoder换行解码器:默认以\n作为分割。()
*/
public static void testLineBasedFrameDecoder(){
final ByteBuf buffer = getByteBufByDelimiter('\n');
// LineBasedFrameDecoder:换行解码器。这里构造器中填写的是检测最大长度,若是超过最大长度还检测不到直接抛异常
final EmbeddedChannel channel = new EmbeddedChannel(new LineBasedFrameDecoder(11), new LoggingHandler());
// 模拟入站操作
channel.writeInbound(buffer);
}
private static ByteBuf getByteBufByDelimiter(char delimiter) {
final ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
log.debug("buffer:{}",buffer.capacity());
Random r = new Random();
char c = 'a';
for (int i = 0; i < 10; i++) {
buffer.writeBytes(makeRandomBytes(r, c, delimiter));
c++;
}
return buffer;
}
/**
* 构造随机长度的字节数组末尾添加分隔符"\n"作为区分
* @param r
* @param c 随机字符
* @param delimiter 界定符
* @return
*/
public static byte[] makeRandomBytes(Random r, char c, char delimiter){
final int num = r.nextInt(10) + 1;
final byte[] data = new byte[num + 1];
//填充[0, num)区间
Arrays.fill(data, 0, num, (byte) c);
data[num] = (byte) delimiter;
System.out.println(new String(data));
return data;
}
}
结果:
④LTC解码器(基于长度字段的帧解码器,长度+内容组成)
四个基础字段分析
LTC解码器:LengthFieldBasedFrameDecoder(基于长度字段的帧解码器)
两个部分组成:[长度,内容]。其中要设置一些值。四个参数:①偏记录长度的偏移量;②长度本身占用的字节数;③调整长度,长度之后有几个字节才是内容;④从头开始省略掉的字节数量。
lengthFiedldOffest:长度字段偏移量
lengthFieldLength:长度字段长度
lengthAdjustment:长度字段为基准,还有几个字节是内容
initialBytesToStrip:从头剥离几个字节
1)源码demo分析:
// 整条消息是14个字节,头部占了2个字节表示内容的长度。
// lengthFieldLength=2:意思是告知该解码器,我的head头部占用了两个字节去解析它拿到内容的长度,那么就能够解析指定边界的一条消息。
* <b>lengthFieldOffset</b> = <b>0</b>
* <b>lengthFieldLength</b> = <b>2</b>
* lengthAdjustment = 0
* initialBytesToStrip = 0 (= do not strip header)
*
* BEFORE DECODE (14 bytes) AFTER DECODE (14 bytes)
* +--------+----------------+ +--------+----------------+
* | Length | Actual Content |----->| Length | Actual Content |
* | 0x000C | "HELLO, WORLD" | | 0x000C | "HELLO, WORLD" |
* +--------+----------------+ +--------+----------------+
// 0202:基于第一个demo,initialBytesToStrip=2也就是最后解析出来过滤掉前2个字节,也就是head头部,最终直接取得对应内容。
* BEFORE DECODE (14 bytes) AFTER DECODE (12 bytes)
* +--------+----------------+ +----------------+
* | Length | Actual Content |----->| Actual Content |
* | 0x000C | "HELLO, WORLD" | | "HELLO, WORLD" |
* +--------+----------------+ +----------------+
// 2300:实际上有些协议还会带上一些魔术字以及其他内容,该案例里多增加了一个head 1部分(length左边),lengthFieldOffset=2表示的是最前面多增加了2个字节长度的字段,lengthFieldLength=3则是表示内容长度的值所占用的字节数,这里的话最终解析出来就是完整的一条 新字段+内容长度+内容的一条消息
* BEFORE DECODE (17 bytes) AFTER DECODE (17 bytes)
* +----------+----------+----------------+ +----------+----------+----------------+
* | Header 1 | Length | Actual Content |----->| Header 1 | Length | Actual Content |
* | 0xCAFE | 0x00000C | "HELLO, WORLD" | | 0xCAFE | 0x00000C | "HELLO, WORLD" |
* +----------+----------+----------------+ +----------+----------+----------------+
//0320:lengthAdjustment=2,表示在长度Length之后偏移指定字节开始读取指定长度的内容。你可以看到此时header1在length长度的右边,这就是lengthAdjustment用处。
* BEFORE DECODE (17 bytes) AFTER DECODE (17 bytes)
* +----------+----------+----------------+ +----------+----------+----------------+
* | Length | Header 1 | Actual Content |----->| Length | Header 1 | Actual Content |
* | 0x00000C | 0xCAFE | "HELLO, WORLD" | | 0x00000C | 0xCAFE | "HELLO, WORLD" |
* +----------+----------+----------------+ +----------+----------+----------------+
//综合案例
* BEFORE DECODE (16 bytes) AFTER DECODE (13 bytes)
* +------+--------+------+----------------+ +------+----------------+
* | HDR1 | Length | HDR2 | Actual Content |----->| HDR2 | Actual Content |
* | 0xCA | 0x000C | 0xFE | "HELLO, WORLD" | | 0xFE | "HELLO, WORLD" |
* +------+--------+------+----------------+ +------+----------------+
//分析:总共有四个部分(各个部分字节长度为1 3 1 12),那么想要读取到内容长度为多少需要一开始就偏移1个字节(lengthFieldOffset),接着我们需要确定内容的真实长度就需要解析3个字节(lengthFieldLength)的表示长度的数字(解析出来知道了有12字节为内容),紧接着由于Length之后还有一个额外字段,想要读取到内容还需要基于Length之后再偏移1个字节(lengthAdjustment)开始读取。最终实际读取写入到ByteBuf是Length之后的内容,那么我们需要剥离HDR1 和 Length部分,也就是3个字节(initialBytesToStrip)
//最终:为1213
2)实际案例
有了这四个部分其实我们就可以自己去定义一些协议了!
案例目的:测试LengthFieldBasedFrameDecoder对指定内容长度的解析!
包含两个demo
组合一:length msg,最终取出msg。
组合二:head1 length head2 msg,最终取出msg。
代码
package cn.com.agree.netty.demo.sthalfpackage;
/**
* @version 1.0
* @ClassName Test4
* @Description TODO 类描述
* @date 2024/4/30 10:10 上午
**/
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Test4 {
public static void main(String[] args) {
test01();
// test02();
}
/**
* demo2:读取(head1 length head2 msg)组合中的msg
*/
public static void test02(){
LengthFieldBasedFrameDecoder decoder = new LengthFieldBasedFrameDecoder(1024, 1, 4, 1, 6);
EmbeddedChannel channel = new EmbeddedChannel(decoder, new LoggingHandler(LogLevel.DEBUG));
ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
//插入三条数据
writeMsg2(buffer, "changlu");
writeMsg2(buffer, "liner");
writeMsg2(buffer, "love");
System.out.println("\n---------------------------发送数据-----------------------------");
log.debug("buffer:{}",buffer);
System.out.println("---------------------------发送数据-----------------------------\n");
channel.writeInbound(buffer);
}
/**
* demo1:读取(length msg)组合中的msg
*/
public static void test01(){
//构造参数:1024 0 4 0 4,参数一指的是检测最大容量,之后则是基础四个配置参数 lengthFieldLength(长度字段长度) initialBytesToStrip(从头剥离4个字节)
LengthFieldBasedFrameDecoder decoder = new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4);
EmbeddedChannel channel = new EmbeddedChannel(decoder, new LoggingHandler(LogLevel.DEBUG));
ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
//插入两条数据
writeMsg1(buffer, "zhangsan");
writeMsg1(buffer, "lines");
System.out.println("\n---------------------------发送数据-----------------------------");
log.debug("buffer:{}",buffer);
System.out.println("---------------------------发送数据-----------------------------\n");
channel.writeInbound(buffer);
}
/**
* 内容组成:length msg
* @param buffer
* @param msg
*/
private static void writeMsg1(ByteBuf buffer, String msg) {
final int length = msg.length();
buffer.writeInt(length);//实际长度:注意这里writeint写的是int类型,占用四个字节
buffer.writeBytes(msg.getBytes());//实际内容
}
/**
* 内容组成 head1 length head2 msg
* @param buffer
* @param msg
*/
private static void writeMsg2(ByteBuf buffer, String msg) {
final int length = msg.length();
int head1 = 1;
int head2 = 2;
//写入四个内容:head1 length head2 msg,最终要读取到msg信息
buffer.writeByte(head1);
buffer.writeInt(length);//实际长度:注意这里writeint写的是int类型,占用四个字节
buffer.writeByte(head2);
buffer.writeBytes(msg.getBytes());//实际内容
}
}
test01测试结果
test02测试结果