typora-copy-images-to: image
TCP粘包/拆包问题的解决之道
项目代码以及笔记同步在 gitee开源仓库中
一、TCP粘包/拆包
什么是TCP粘包和拆包?
答:TCP是个“流”协议,所谓流,就是没有界限的的遗传数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以实际业务的一个完整的包可能会被TCP拆分成多个包进行发送,也可能把多个小包打包成一个大包发送。
1.1 TCP粘包/拆包问题说明
如图示例:
假设客户端分别发送了两个数据包D1和D2给服务端,由于服务端读取到的字节数是不确定的,因此存在以下四种情况:
- 服务端分两次读取到两个独立的数据包,分别是D1和D2,没有粘包和拆包的现象。
- 服务端一次性接收到两个数据包,D1和D2粘在一起,被称为TCP粘包。
- 服务端分两次读取到两个数据包,第一次读取到完整的D1包和部分D2包,第二次读取到剩余部分的D2包,被称为TCP拆包。
- 服务端第一次读取到部分D1包,第二次读取到剩下的D1包和完整的D2包。
如果数据包D1和D2非常大,抑或是TCP接收滑窗非常小,很可能会发生第五种情况:服务端分多次才能将D1、D2包完全接收,期间发生多次拆包。
1.2 TCP粘包/拆包发生的原因
问题的产生有三个:
- 应用程序write写入的字节大小大于套字节发送缓冲区的大小
- 进行MSS大小的TCP分段
- 以太网帧的payload大于MTU进行IP分片。
1.3 粘包问题的解决策略
由于底层的TCP无法理解上层的业务数据,所以在底层无法保证数据包不被拆分和重组,这个问题只能通过上层应用协议栈来解决,根绝业界的主流协议的解决方案,可以归纳如下:
- 消息定长,例如每个报文的大小为固定长度200字节,如果不够,空位补空格。
- 在包尾加回车换行符进行分割,例如FTP协议。
- 将消息分为消息头和消息体,消息头中包含了消息的总长度,通常设计思路为消息头的第一个字段使用int32来表示消息的总长度。
- 更复杂的应用协议。
二、Netty未考虑粘包所导致的异常案例
在上一章的时间服务器的案例中,就没有考虑读半包的问题,这在功能测试中没有问题,但压力一旦上来了,或者发送大报文之后,就会存在粘包/拆包问题。如果代码没有考虑,就会出现解码错位或者错误,导致程序不能正常工作。
2.1 TimeServer的改造
时间服务端,TimeServerHandler的改造:
public class TimeServerHandler extends ChannelHandlerAdapter {
private int counter = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//这里进行转换,因为ByteBuf提供了更强大灵活的功能
ByteBuf buf = (ByteBuf) msg;
//readableBytes()方法可以获取缓冲区可读的字节数,以此创建一个合适大小的byte数组
byte[] bytes = new byte[buf.readableBytes()];
//readBytes方法将buf中缓存的字节复制到新建的bytes数组中
buf.readBytes(bytes);
//将数组转为字符
String s = new String(bytes, StandardCharsets.UTF_8);
System.out.println("The time is " + s + ";the counter is " + ++counter);
//QUERY TIME ORDER这串字符是客户端发送过来的,这里判断请求消息来源,如果是客户端的消息,则将正确时间赋值给currentTime
String currentTime = ("QUERY TIME ORDER" + System.lineSeparator()).equalsIgnoreCase(s) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
//转为ByteBuf对象
ByteBuf byteBuf = Unpooled.copiedBuffer(currentTime.getBytes());
//异步发送应答消息给客户端
ctx.write(byteBuf);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
改动的地方在于,每次应答都会计数。按照设计,服务端接收到的消息总数应该与客户端发送的消息总数相同,并且返回正确的消息体:“QUERY TIME ORDER”。
2.2 TimeClient的改造
时间客户端TimeClientHandler的改造:
public class TimeClientHandler extends ChannelHandlerAdapter {
private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
private byte[] req;
public TimeClientHandler() {
//System.lineSeparator()是换行符,使用这个可以屏蔽windows和Linux的区别
req = ("QUERY TIME ORDER" + System.lineSeparator()).getBytes();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf message = null;
for (int i = 0; i < 100; i++) {
message = Unpooled.buffer(req.length);
message.writeBytes(req);
ctx.writeAndFlush(message);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String s = new String(bytes, StandardCharsets.UTF_8);
System.out.println("Now is : " + s);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//释放资源
logger.warning("Unexpected exception from downstream : " + cause.getMessage());
ctx.close();
}
}
这里的改动,主要是客户端与服务端链路建立成功之后,循环发送100条消息,每发送一条就刷新一次,保证每条消息都写入Channel中。我们预想的情况是客户端发送100条数据都能够得到正确回应。
运行查看实际:
服务端:
The time is QUERY TIME ORDER
QUERY TIME ORDER
QUERY TIME ORDER
QUERY TIME ORDER
--------省略--------
QUERY TIME ORDER;the counter is 1
--------省略--------
;the counter is 2
客户端:
Now is : BAD ORDERBAD ORDERSun Jun 23 23:09:09 CST 2024BAD ORDERBAD ORDER
this count is : 1
实际情况为:服务端仅仅收到两条消息,,第一条包含57条“QUERY TIME ORDER”指令,第二条包含了43条“QUERY TIME ORDER”指令。这说明发生了TCP粘包,而客户端收到的回复也仅仅只有一条消息,为多个消息粘合在一起,说明服务端返回的消息也发生了粘包。
由于上面的例子没有考虑TCP的粘包/拆包问题,所以当发生TCP粘包的时候,我们的程序就不能正常工作了。
三、利用LineBasedFrameDecoder解决TCP粘包的问题
为了解决TCP粘包/拆包问题导致的半包读写问题,Netty默认提供了多种解码器用于处理半包,只要熟练掌握这些类库的使用,TCP粘包的问题从此变得非常简单,你甚至不用关心他们,这也是其他NIO框架和原生的NIO API所无法匹敌的。
3.1 服务端
TimeServer:
public class TimeServer {
public void bind(int port) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new TimeServerHandler());
}
});
//绑定端口,等待同步成功
ChannelFuture f = b.bind(port).sync();
//等待监听端口关闭
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080;
if(args != null && args.length > 0) {
try {
port = Integer.parseInt(args[0]);
}catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
new TimeServer().bind(port);
}
}
修改的重点就在于,在处理IO事件的类中,新增了两个解码器LineBasedFrameDecoder和StringDecoder。
TimeServerHandler:
public class TimeServerHandler extends ChannelHandlerAdapter {
private int count;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("The Time server receive order : " + body + " ; The count is " + ++count);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
currentTime += System.lineSeparator();
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.writeAndFlush(resp);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
而在TimeServerHandler中,我们几乎没有做其他改变,因为在TimeServerHandler中已经做了处理,不需要额外考虑是否读半包的问题。
3.2 客户端
TimeCilent:
public class TimeCilent {
public void connect (int port,String host) throws InterruptedException {
//配置客户端NIO线程组
NioEventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.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 LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeClientHandler());
}
});
//发起异步连接
ChannelFuture f = b.connect(host,port).sync();
//等待关闭
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080;
if(args != null && args.length > 0){
try {
port = Integer.parseInt(args[0]);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
new TimeCilent().connect(port,"127.0.0.1");
}
}
客户端也一样,在IO事件处理类中加入了LineBasedFrameDecoder和StringDecoder解码器。
TimeClientHandler:
public class TimeClientHandler extends ChannelHandlerAdapter {
private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
private int count = 0;
private byte[] req;
public TimeClientHandler() {
req = ("QUERY TIME ORDER" + System.lineSeparator()).getBytes();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf message = null;
for (int i = 0; i < 100; i++) {
message = Unpooled.buffer(req.length);
message.writeBytes(req);
ctx.writeAndFlush(message);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("Now is : " + body + "; The count is : " + ++count);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.warning("Unexpected exception from downstream : " + cause.getMessage());
ctx.close();
}
}
四、重新运行
程序的运行完全符合预期,说明LineBasedFrameDecoder和StringDecoder成功解决了TCP粘包导致的读半包的问题。
五、LineBaseFrameDecoder和StringDecoder的原理
LineBasedFrameDecoder的工作原理就是它依次遍历ByteBuf中的可读字节,判断看是否有\n
或者\r\n
,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成了一行。它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符的两种解码方式,同事支持配置单行的最大长度。如果读取到最大长度后仍未读取到换行符,就会抛出异常,同时忽略掉之前读到的异常码流。
StringDecoder的功能非常简单,就是将接收到的对象转换成字符串,然后继续调用后面的Handler。LineBasedFrameDecoder+StringDecoder就是组合就是按行切换的文本解码器,它被用来设计支持TCP的粘包和拆包。
如果我们的消息不是用换行来结束的呢?
Netty提供了多种支持TCP粘包/拆包的解码器,用来满足用户的不同诉求。这是后话了。