TCP粘包/拆包

TCP粘包/拆包

Tags: Netty

摘要

NIO编程中如果没有考虑读半包的问题,一旦压力上来,或者发送大报文,就会存在粘包/拆包的问题。

粘包原因

NIO编程中如果没有考虑读半包的问题,一旦压力上来,或者发送大报文,就会存在粘包/拆包的问题。

粘包主流解决方案

  1. 消息定长, 不足补 0
  2. 在包尾增加回车换行符, 如 FTP
  3. 将消息分为消息头和消息体, 消息头中包含表示消息总长度(或者消息体总长度)的字段,通常设计思路为消息头中的第一个字段使用 int32 表示总长度。
  4. 更复杂的应用层协议

模拟粘包场景

server
 ------------------------
 The time server receive order : QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORD ; the counter is : 1
 The time server receive order :
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER
 QUERY TIME ORDER ; the counter is : 2



 client
 ------------------
 Now is : BAD ORDER
 BAD ORDER
 ; the counter is : 1

日志分析

按照程序设计, 客户端应该接收到 100 条当前系统的时间消息,但实际上只收到了一条。因为服务器只收到了 2 条请求,并返回了 2 条 “BAD ORDER”应答。但实际客户端只收到了 1条。表明服务器端也发生了粘包。

源码地址

https://coding.net/u/javacore/p/netty_combinepkg_unpkg/git