Netty解决TCP拆包粘包
当客户端或服务端读取(发送)消息的时候,都要考虑TCP底层的粘包/拆包机制。本文将从介绍TCP底层的粘包/拆包机制开始,逐步深入到Netty如何解决这个问题。
# TCP粘包/拆包
TCP是个“流”协议,所谓流,就是没有界限的一串数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情況进行包的划分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。
# TCP粘包/拆包问题说明
假设客户端向服务器发送两个数据包D1与D2,由于服务端一次读取到的字节数是不一样的。因而产生以下四种情况:
- 服务端分两次读取到了两个独立的数据包,分别是D1和D2,没有粘包和拆包;
- 服务端一次接收到了两个数据包,D1和D2粘合在一起,被称为TCP粘包;
- 服务端分两次读取到了两个数据包,第一次读取到了完整的D1包和D2包的部分内容,第二次读取到了D2包的剩余内容,这被称为TCP拆包;
- 服务端分两次读取到了两个数据包,第一次读取到了D1包的部分内容D1_1,第二次读取到了D1包的剩余内容D1_2和D2包的整包。
如果此时服务端TCP接收滑窗非常小,而数据包D1和D2比较大,很有可能会发生第五种可能,即服务端分多次才能将D1和D2包接收完全,期间发生多次拆包。
# TCP粘包/拆包产生的原因
- 应用程序wrie写入的字节大小大于套接口发送缓冲区大小;
- 进行 MSS 大小的TCP分段;
- 以太网帧的 payload 大于 MTU 进行IP分片。
# TCP粘包/拆包解决策略
这个问题只能通过上层的应用协议栈设计来解决,根据业界的主流协议的解决方案,可以归纳如下:
- 消息定长,例如每个报文的大小为固定长度200字节,如果不够,空位补空格
- 在包尾增加回车换行符进行分割,例如FTP协议
- 将消息分为消息头和消息体,消息头中包含表示消息总长度(或者消息体长度)的字段,通常设计思路为消息头的第一个字段使用int32来表示消息的总长度:;
- 更复杂的应用层协议。
# 应用案例
接下来,我们将深入实践如何解决TCP粘包/拆包。
# 未考虑TCP粘包导致功能异常
省略服务端和客户端构建netty启动器代码。以下代码皆为handler处理器。
服务端代码:
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
private int count = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body = new String(bytes,"UTF-8")
.substring(0,bytes.length - System.getProperty("line.separator").length());
System.out.println("The time server receive order : " + body + "; the count is " + (++ count));
String curr = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
new Date(System.currentTimeMillis()).toString() : "BACK ORDER";
curr = curr + " >>> " +System.getProperty("line.separator");
ByteBuf resp = Unpooled.copiedBuffer(curr.getBytes());
ctx.writeAndFlush(resp);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
每读到一条消息后,就计一次数,然后发送应答消息给客户端。按照设计,服务端接收到的消息总数应该跟客户端发送的消息总数相同,而且请求消息删除回车换行符后应该勺" QUERY TIME ORDER"。
客户端代码:
public class TimeClientChannelHandler extends ChannelInboundHandlerAdapter {
private int count;
private byte[] req;
TimeClientChannelHandler() {
req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buf = null;
for (int i = 0; i < 100; i++) {
buf = Unpooled.buffer(req.length);
buf.writeBytes(req);
ctx.writeAndFlush(buf);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body = new String(bytes, "UTF-8");
System.out.println("Now is: " + body + "; the count is" + ++count);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
客户端跟服务端链路建立成功之后,循环发送100条消息,每发送一条就刷新一次,保证每条消息都会被写入 Channel中。按照我们的设计,服务端应该接收到100条查询时间指令的请求消息。客户端每接收到服务端一条应答消息之后,就打印一次计数器。
服务端输出:
Server:
...
QUERY TIME ORDER
QUERY TIME ORD and the count is 1
The time server receive order:
QUERY TIME ORDER
QUERY TIME ORDER
...
QUERY TIME ORDER
QUERY TIME ORDER and the count is 2
2
3
4
5
6
7
8
9
10
11
服务端运行结果表明它只接收到了两条消息,第一条包含57条“ QUERY TIMEORDER"指令,第二条包含了43条“ QUERY TIME ORDER”指令,总数正好是100条我们期待的是收到100条消息,每条包含一条“ QUERY TIME ORDER”指令。这说明发生了TCP粘包。按照设计初衷,客户端应该收到100条当前系统时间的消息。
客户端输出:
Now is: BACK ORDER >>>
BACK ORDER >>>
and the count is 1
2
3
按照设计初衷,客户端应该收到100条当前系统时间的消息,但实际上只收到了一条。这不难理解,因为服务端只收到了2条请求消息,所以实际服务端只发送了2条应答,由于请求消息不满足查询条件,所以返回了2条“BACK ORDER”应答消息。
但是实际上客户端只收到了一条包含2条“BACK ORDER”指令的消息,说明服务端返回的应答消息也发生了粘包由于上面的例程没有考虑TCP的粘包/拆包,所以当发生TCP粘包时,我们的程序就不能正常工作。
下面的章节将演示如何通过Nety的 Line Basedframedecoder和 String Decoder来解决TCP粘包问题。
# 使用解决TCP的粘包/拆包
为了解决TCP粘包/拆包导致的半包读写问题,Nety默认提供了多种编解码器用于处理半包,只要能熟练掌握这些类库的使用,TCP粘包问题从此会变得非常容易,你甚至不需要关心它们,这也是其他NIO框架和JDK原生的 NIO API所无法匹敌的。
服务端代码:
public class TimeServer {
public void run(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
//修改前
//ch.pipeline().addLast(new TimeServerHandler());
// 修改后:
ch.pipeline().addLast(new LineBasedFrameDecoder(1024))
.addLast(new StringDecoder())
.addLast(new TimeServerHandler());
}
});
ChannelFuture future = server.bind(port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
TimeServer server = new TimeServer();
server.run(8090);
}
}
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
private int count = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("The time server receive order: " + body + " and the count is " + (++ count));
String curr = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
new Date(System.currentTimeMillis()).toString() : "BACK ORDER";
curr = curr + " >>> " +System.getProperty("line.separator");
ByteBuf resp = Unpooled.copiedBuffer(curr.getBytes());
ctx.writeAndFlush(resp);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
客户端代码:
public class TimeClient {
public void run(String host, int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
try {
Bootstrap client = new Bootstrap();
client.group(bossGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
//修改前
//ch.pipeline().addLast(new TimeClientChannelHandler());
// 修改后:
ch.pipeline()
.addLast(new LineBasedFrameDecoder(1024))
.addLast(new StringDecoder())
.addLast(new TimeClientChannelHandler());
}
});
ChannelFuture future = client.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
TimeClient client = new TimeClient();
client.run("127.0.0.1", 8090);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
服务端输出:
The time server receive order: QUERY TIME ORDER and the count is 1
The time server receive order: QUERY TIME ORDER and the count is 2
....
The time server receive order: QUERY TIME ORDER and the count is 99
The time server receive order: QUERY TIME ORDER and the count is 100
2
3
4
5
客户端输出:
Now is: Mon Sep 14 20:39:18 CST 2020 >>> and the count is 1
Now is: Mon Sep 14 20:39:18 CST 2020 >>> and the count is 2
....
Now is: Mon Sep 14 20:39:18 CST 2020 >>> and the count is 99
Now is: Mon Sep 14 20:39:18 CST 2020 >>> and the count is 100
2
3
4
5
提示
通过使用 LineBasedframedecoder 和 Stringdecoder 成功解决了TCP粘包导致的读半包问题。对于使用者来说,只要将支持半包解码的handler添加到 Channel Pipeline 中即可,不需要写额外的代码,用户使用起来非常简单。
# LineBasedFrameDecoder和StringDecoder原理分析
LineBasedFrameDecoder的工作原理是它依次遍历 Bytebuf 中的可读字节,判断看是否有“n”或者“rn"”,如果有,就以此位置为结束位置,从可读索引到结東位置区间的字节就组成了一行。
它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符两种解码方式,同时支持配置单行的最大长度。如果连续读取到最大长度后仍然没有发现换行符,就会抛出异常,同时忽略掉之前读到的异常码流。
StringDecoder的功能非常简单,就是将接收到的对象转换成字符串,然后继续调用后面的 handler。LineBasedFrameDecoder + StringDecoder组合就是按行切换的文本解码器,它被设计用来支持TCP的粘包和拆包。
可能读者会提出新的疑问:如果发送的消息不是以换行符结束的该怎么办呢?或者没有回车换行符,靠消息头中的长度字段来分包怎么办?是不是需要自己写半包解码器?答案是否定的, Netty提供了多种支持TCP粘包/拆包的解码器,用来满足用户的不同诉求。