戳蓝字「TopCoder」关注我们哦!
编者注:学习netty处理黏包和拆包,首先要知道什么是黏包和拆包问题?
黏包和拆包的产生是由于TCP拥塞控制算法(比如angle算法)和TCP缓冲区机制导致的,angle算法简单来说就是通过一些规则来尽可能利用网络带宽,尽可能的发送足够大的数据。TCP(发送/接收)缓冲区会暂缓数据,并且是有最大容量的。
黏包的产生是由于一次TCP通信数据量较少,导致多个TCP数据合并在一起(这里的合并可能发生在发送缓冲区合并后发送,也可能发生在接收缓冲区合并后应用程序一次性读取)。拆包的产生是由于一次TCP通信数据量较大(比如超过了MTU),导致发送时分片发送,这样接收时是多次接收后才是一个完整的数据。
netty处理黏包和拆包问题,思路就是以定长方式读取接收到的数据来处理(比如读取固定长度数据量、以TLV方式读取数据、以固定分隔符读取数据等)。
下面以一个定长方式读取数据的示例来分析下Netty的处理机制,server端处理TCP黏包和拆包示例代码:
1EventLoopGroup bossGroup = new NioEventLoopGroup(1);
2EventLoopGroup workerGroup = new NioEventLoopGroup();
3try {
4 ServerBootstrap boot = new ServerBootstrap();
5 boot.group(bossGroup, workerGroup)
6 .channel(NioServerSocketChannel.class)
7 .localAddress(60000)
8 .childHandler(new ChannelInitializer<SocketChannel>() {
9 @Override
10 protected void initChannel(SocketChannel ch) throws Exception {
11 ch.pipeline()
12 // 定长接收消息,用于处理黏包分包问题
13 .addLast(new FixedLengthFrameDecoder(1))
14 .addLast(new EchoHandler());
15 }
16 });
17
18 // start
19 ChannelFuture future = boot.bind().sync();
20 future.channel().closeFuture().sync();
21} catch (Exception e) {
22 e.printStackTrace();
23} finally {
24 // shutdown
25 bossGroup.shutdownGracefully();
26 workerGroup.shutdownGracefully();
27}
FixedLengthFrameDecoder类继承关系如下,下面就以该类为例讲解下netty 处理粘包分包机制。
这里思考一下,如果接收到的数据未达到FixedLengthFrameDecoder要求的长度,这个时候Netty该如何处理呢?
首先可以肯定的一点是,接收到数据长度不够,是不会进行后续channelHandler处理的。Netty的处理机制是会将接收到的数据存储到ByteToMessageDecoder.cumulation
中,暂存一下,等待下次接收到数据时继续处理直到达到要求长度之后才交给后续的ChannelHandler来处理,ByteToMessageDecoder代码如下:
1// ByteToMessageDecoder
2public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
3 if (msg instanceof ByteBuf) {
4 CodecOutputList out = CodecOutputList.newInstance();
5 try {
6 ByteBuf data = (ByteBuf) msg;
7 first = cumulation == null;
8 if (first) {
9 cumulation = data;
10 } else {
11 // cumulation保存有上次未处理(不完整)的数据
12 cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);
13 }
14 callDecode(ctx, cumulation, out);
15 } catch (DecoderException e) {
16 throw e;
17 } catch (Exception e) {
18 throw new DecoderException(e);
19 } finally {
20 if (cumulation != null && !cumulation.isReadable()) {
21 numReads = 0;
22 cumulation.release();
23 cumulation = null;
24 } else if (++ numReads >= discardAfterReads) {
25 numReads = 0;
26 discardSomeReadBytes();
27 }
28
29 int size = out.size();
30 decodeWasNull = !out.insertSinceRecycled();
31 // 继续回调channelHandler.channelRead
32 fireChannelRead(ctx, out, size);
33 out.recycle();
34 }
35 } else {
36 ctx.fireChannelRead(msg);
37 }
38}
39
40final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
41 throws Exception {
42 decodeState = STATE_CALLING_CHILD_DECODE;
43 try {
44 decode(ctx, in, out);
45 } finally {
46 boolean removePending = decodeState == STATE_HANDLER_REMOVED_PENDING;
47 decodeState = STATE_INIT;
48 if (removePending) {
49 handlerRemoved(ctx);
50 }
51 }
52}
53protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
54 Object decoded = decode(ctx, in);
55 if (decoded != null) {
56 out.add(decoded);
57 }
58}
59// 已接收数据未达到要求的长度时,继续等待接收
60protected Object decode(
61 @SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
62 if (in.readableBytes() < frameLength) {
63 return null;
64 } else {
65 return in.readRetainedSlice(frameLength);
66 }
67}
处理粘包拆包,其实思路都是一致的,就是“分分合合”,粘包由于数据过多,那就按照固定策略分割下交给程序来处理;拆包由于一次传输数据较少,那就等待数据传输长度够了再交给程序来处理。
推荐阅读
欢迎小伙伴关注【TopCoder】阅读更多精彩好文。