netty大数据量传输停止_再也不怕问 Netty 黏包拆包机制了

24a0743320ac7b1d3d0d0f1b3900d481.png

学习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() { 9 @Override10 protected void initChannel(SocketChannel ch) throws Exception {11 ch.pipeline()12 // 定长接收消息,用于处理黏包分包问题13 .addLast(new FixedLengthFrameDecoder(1))14 .addLast(new EchoHandler());15 }16 });1718 // start19 ChannelFuture future = boot.bind().sync();20 future.channel().closeFuture().sync();21} catch (Exception e) {22 e.printStackTrace();23} finally {24 // shutdown25 bossGroup.shutdownGracefully();26 workerGroup.shutdownGracefully();27}

FixedLengthFrameDecoder类继承关系如下,下面就以该类为例讲解下netty 处理粘包分包机制。

245ea1d19c89e1d5c62ade5beaf05893.png

这里思考一下,如果接收到的数据未达到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 }2829 int size = out.size();30 decodeWasNull = !out.insertSinceRecycled();31 // 继续回调channelHandler.channelRead32 fireChannelRead(ctx, out, size);33 out.recycle();34 }35 } else {36 ctx.fireChannelRead(msg);37 }38}3940final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List 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 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}

处理粘包拆包,其实思路都是一致的,就是“分分合合”,粘包由于数据过多,那就按照固定策略分割下交给程序来处理;拆包由于一次传输数据较少,那就等待数据传输长度够了再交给程序来处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值