填坑系列——TCP/IP中的Nagle算法

问题:

          写交易所模拟网关发送工具时,测得快照全链路时间200多微,逐笔80多微。时间异常的大,通过查找分析发现TCP默认开启Nagle算法,未设置TCP_NODELAY将缓存等待的时间计算进去导致时间过大。

分析:

TCP/IP协议中针对TCP默认开启了Nagle算法。Nagle算法通过减少需要传输的数据包,提高网络的利用率,来优化网络。对于延时敏感型同时数据传输量较小的应用可以开启TCP_NODELAY选项。开启Nagle算法,数据缓存到一定量后,才会发送出去,这样不可避免的增加了延迟。与TCP Delayed ACK延迟确认机制(1、有响应数据时,ACK附带响应数据一起发送给对方2、没有响应数据,等待一个延迟 Delay Time后发送)特性结合,延迟会更加显著,基本在40ms左右。这个现象只会在进行连续两次写操作时候体现。

摘自Wikipedia的Nagle算法的伪码实现:

if there is new data to send
  if the window size >= MSS and available data is >= MSS
    send complete MSS segment now
  else
    if there is unconfirmed data still in the pipe
      enqueue data in the buffer until an acknowledge is received
    else
      send data immediately
    end if
  end if
end if

通过这段伪代码,发现对于读-写-读-写模式,关闭TCP_NODELAY问题不大。连续多次小数据包写操作,然后读,应该在应用层进行优化。

实现

#include <netinet/tcp.h>

int optval = 1;
if(setsockopt(server_sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)))
{
    perror("set tcp nodelay:");
    exit(1);
}

参考文献:

https://www.zhihu.com/question/42308970

https://blog.csdn.net/asklw/article/details/79246959

https://blog.csdn.net/historyasamirror/article/details/6423235

https://blog.csdn.net/historyasamirror/article/details/6122284

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值