一、Netty常用解码器
TCP以流的形式传输数据,上层协议为了对消息进行区分,常采用以下4种方式:
- 回车换行符:将回车换行符作为消息结束标志,如FTP协议,这种方式在文本协议中应用较为广泛;
- 特殊分隔符:将特殊分隔符作为消息结束标志,上述的回车换行符就是一种特殊的特殊分隔符;
- 固定消息长度:设置一个定值LEN,当累计读取到长度为LEN的报文后就认为读取了一个完整的消息;将计数器置位重新读取下一个数据报文;
- 消息头定长:在消息头中定义长度标识消息总长度。
Netty提供了4种常用解码器:
- LineBasedFrameDecoder - 换行解码器
- DelimiterBasedFrameDecoder - 分隔符解码器
- FixedLengthFrameDecoder - 定长解码器
- LengthFieldBasedFrameDecoder - 消息头定长解码器
下面将逐一通过demo演示4种解码器对粘包问题的支持。
二、Netty常用解码器代码演示
2.1 LineBasedFrameDecoder
LineBasedFrameDecoder是基于行分割的解码器,使用的分隔符为windows下的\r\n
或linux的\n
属于特殊的分隔符解码器。
LineBasedFrameDecode中成员变量:
/**最大解码帧长度,超过此长度还未找到分隔符将会抛出TooLongFrameException异常 */
private final int maxLength;
/** 是否快速失败;true-超过maxLength快速抛出异常; false-超过maxLength读完整帧再抛出异常 */
private final boolean failFast;
// 返回的解析结果中是否包含分隔符
private final boolean stripDelimiter;
/**超过最大帧长度是否丢弃字节 */
private boolean discarding;
/**丢弃的帧长度 */
private int discardedBytes;
LineBasedFrameDecode的代码示例在上节已经演示过,本文就不在演示。
2.2 DelimiterBasedFrameDecoder
1、定义
DelimiterBasedFrameDecoder是基于分隔符的解码器。
DelimiterBasedFrameDecoder解码器在接收到ByteBufs后,根据自定义的分隔符进行分割。
2、分隔符
DelimiterBasedFrameDecoder支持自定义一个或多个分隔符。如果在消息中发现多个分隔符,会选择能产生最短帧的分隔符。
如:
以下字符串中包含\n
和\r\n
两个分隔符。
ABC\nDEF\r\n
(1) DelimiterBasedFrameDecoder采用\n
作为分隔符后的结果为:
ABC | DEF
(2) DelimiterBasedFrameDecoder采用\r\n
作为分隔符后的结果为:
ABC\nDEF
采用\n
产生的帧长度比采用\r\n
产生的帧长度短,
所以 DelimiterBasedFrameDecode采用\n
分隔符。
3、默认分隔符
DelimiterBasedFrameDecode有两种默认分隔符:NUL分隔符和行分隔符.
public static ByteBuf[] nulDelimiter() {
return new ByteBuf[] {
Unpooled.wrappedBuffer(new byte[] {
0 }) };
}
public static ByteBuf[] lineDelimiter() {
return new ByteBuf[] {
Unpooled.wrappedBuffer(new byte[] {
'\r', '\n' }),
Unpooled.wrappedBuffer(new byte[] {
'\n' }),
};
}
4、代码演示
服务端:
package com.wgs.netty.demo3_decoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* Created by wanggenshen
* Date: on 2019/7/13 17:34.
* Description: DelimiterBasedFrameDecoder解码器demo服务端
*/
public class EchoServer {
private static final String DELIMITER_STR = "$_";
public static void bind(int port) throws InterruptedException {
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(parentGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// $_ 分隔符
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline()
// 分隔符解码器
.addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
// Bytebuf解码成字符串对象
.addLast(new StringDecoder())
.addLast(new SimpleChannelInboundHandler() {
// 计数器
int counter = 0;
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// 读取客户端发送的消息
String bodyFromClient = (String) msg;
System.out.println("This msg is from client , content is : 【" + bodyFromClient + "】"
+ ", the counter is : " + ++counter);
// 将读取到的内容再发送给客户端
String bodyToClient = "FROM服务端的消息【" + bodyFromClient + "】" + DELIMITER_STR;
ByteBuf resp = Unpooled.copiedBuffer(bodyToClient.getBytes());
ctx.writeAndFlush(resp);
}
});
}
});
ChannelFuture future = bootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} finally {
parentGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
EchoServer.bind(8080);
}
}
客户端
package com.wgs.netty.demo3_decoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* Created by wanggenshen
* Date: on 2019/7/13 18:18.
* Description: DelimiterBasedFrameDecoder客户端demo
*/
public class EchoClient {
private static final String DELIMITER_STR = "$_";
public static void connect(int port, String host) throws InterruptedException {
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 定义$_ 分隔符
ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER_STR.getBytes());
socketChannel.pipeline()
// 分隔符解码器
.addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
// ByteBuf解码成字符串对象
.addLast(new StringDecoder())
.addLast(new SimpleChannelInboundHandler() {
// 计数器
private int counter;
static final String ECHO_STR = "this is delimiter demo$_";
/**
* 读取服务端响应
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
String bodyFromServer = (String) msg;
System.out.println("The msg is from server, content: " + bodyFromServer
+ ", the times is : " + ++counter);
}
/**
* 发送消息给客户端
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 10; i++) {
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_STR.getBytes()));
}
}
});
}
});
// 发起异步连接
ChannelFuture future = bootstrap.connect(host, port).sync();
// 等待客户端链路关闭
future.channel().closeFuture().sync();
} finally {
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
EchoClient.connect(8080, "