简介
Nagle(纳格)算法通过减少发往网络中小包的数量来提高 TCP/IP 网络效率(利用率)。
- 小包问题
- 假设数据只有 1byte,因为 TCP包有 40byte 的包头,所以当在网络中传输时会使用 41byte 的包。
- 如果一个应用一直发送这种小包,就会造成网络的严重浪费。
这种情况经常发生在 Telnet 中——Telnet 每键入一个单独的数据就会被立刻传输。
伪代码
if there is new data to send thenif the window size ≥ MSS and available data is ≥ MSS thensend complete MSS segment nowelseif there is unconfirmed data still in the pipe thenenqueue data in the buffer until an acknowledge is receivedelsesend data immediatelyend ifend ifend if
- MSS(maximum segment size)
- TCP 的一个 header,它反映了这条 TCP 链接上每一个段的最大长度
- window size
关闭这两个算法中的一个即可解决这个问题,通常会关闭 Nagle 算法。
也可以通过减少 TCP timer 的值,来缓解时延问题。
禁用 Nagle 或者 delayed ACK
- 禁用Nagle
- TCP 的实现通常通过传入
TCP_NODELAY参数来禁用 Nagle 算法。
- TCP 的实现通常通过传入
- 禁用 delayed ACK
TCP_QUICKACK参数通常用来禁用该选项。
以上两个参数可以通过
man tcp获取相关信息。
与 real-time 系统交互
期待 real-time 回复和低时延的应用应该关闭 Nagle 算法。比如大型网络游戏,或者依赖于鼠标控制的远程操作系统。
也可以使用 UDP 来代替 TCP。
参考
https://en.wikipedia.org/wiki/Nagle%27s_algorithm
https://searchnetworking.techtarget.com/definition/Nagles-algorithm
https://blog.csdn.net/wdscq1234/article/details/52432095
https://www.extrahop.com/company/blog/2016/tcp-nodelay-nagle-quickack-best-practices/
