简介
Nagle算法
Nagle算法的问题:在小包传输时可以合并发送,Nagle 算法,用于减少小包发送数量的一种优化算法,目的是为了提高实际带宽的利用率.
Nagle算法定义:
inhibit the sending of new TCP segments when new outgoing data arrives from the user if any previously transmitted data on the connection remains unacknowledged.
伪码:
Where MSS is the maximum segment size, the largest segment that can be sent on this connection, and the window size is the currently acceptable window of unacknowledged data,
if there is new data to send then
if the window size ≥ MSS and available data is ≥ MSS then
send complete MSS segment now
else
if there is unconfirmed data still in the pipe then
enqueue data in the buffer until an acknowledge is received
else
send data immediately
end if
end if
end if
TCP delayed acknowledgment
延时合并发送ack包.
a host may delay sending an ACK response by up to 500 ms. Additionally, with a stream of full-sized incoming segments, ACK responses should be sent for every second segment.
Redhat可以改这个延时配置.其它的发行版本没法改这个配置.默认40ms延时.
解决
在创建TCPSocket时我们可以设置以下的标志位:
TCP_NODELAY
If set, disable the Nagle algorithm. This means that segments are always sent as soon as
possible, even if there is only a small amount of data. When not set, data is buffered
until there is a sufficient amount to send out, thereby avoiding the frequent sending of
small packets, which results in poor utilization of the network. This option cannot be
used at the same time as the option TCP_CORK.
TCP_QUICKACK
Enable quickack mode if set or disable quickack mode if cleared. In quickack mode, acks
are sent immediately, rather than delayed if needed in accordance to normal TCP operation.
This flag is not permanent, it only enables a switch to or from quickack mode. Subsequent
operation of the TCP protocol will once again enter/leave quickack mode depending on
internal protocol processing and factors such as delayed ack timeouts occurring and data
transfer. This option should not be used in code intended to be portable.
开启TCP_NODELAY后就可以禁用Nagle算法,开启TCP_QUICK后就可以避免Linux的延时ACK导致的请求时延的问题.
总结
TCP Nagle算法和Delay ACK结合在一起就会产生不必要的延时,Nagle算法最多有一个待确认的合并包,Delayed ACK会一直延时发送ACK,到了超时时间才会发送,这样就照成每次发送一个合并包都会等一段时间返回ACK.因此网络传输性能在开启两者选项时会急剧下降.