Nagle算法研究

Nagle算法

Nagle算法是以减少封包传送量来增进TCP/IP网络的效能。 它是由约翰.纳格任职于Ford Aerospace时命名。

纳格的文件,Congestion Control in IP/TCP Internetworks (RFC896) 描述了他所谓的“小封包问题”-某个应用程式不断地送出小单位的资料,且某些常只占1字节大小。 因为TCP封包具有40字节的标头资讯(TCP与IPv4各占20字节),这导致了41字节大小的封包只有1字节的可用资讯,造成庞大的浪费。 这种状况常常发生于Telnet工作阶段-大部分的键盘操作会产生1字节的资料并马上送出。 更糟的是,在慢速的网络连线下,这类的封包会大量地在同一时点传输,造成拥塞碰撞(Congestion Collapse)。

Nagle算法的工作方式是合并(coalescing)一定数量的输出资料后一次送出。特别的是,只要有已送出的封包尚未确认,传送者会持续缓冲封包,直到累积一定数量的资料才送出。

 

Nagle算法非常简单,但它能解决问题。这个算法是为发送端的TCP用的:

1. 发送端的TCP将它从发送应用程序收到的第一块数据发送出去,哪怕只有一个字节。

2. 在发送第一个报文段(即报文段1)以后,发送端的TCP就在输出缓存中积累数据,并等待:或者接收端的TCP发送出一个确认,或者数据已积累到可以装成一个最大的报文段。在这个时候,发送端的TCP就可以发送这个报文段。

3. 对剩下的传输,重复步骤2。这就是:如果收到了对报文段x的确认,或者数据已积累到可以装成一个最大的报文段,那么就发送下一个报文段(x + 1)。

 

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
下面看看在LWIP TCPIP中对nagle算法的实现和使用
/**
 * This is the Nagle algorithm: try to combine user data to send as few TCP
 * segments as possible. Only send if
 * - no previously transmitted data on the connection remains unacknowledged or
 * - the TF_NODELAY flag is set (nagle algorithm turned off for this pcb) or
 * - the only unsent segment is at least pcb->mss bytes long (or there is more
 *   than one unsent segment - with lwIP, this can happen although unsent->len < mss)
 * - or if we are in fast-retransmit (TF_INFR)
 */
#define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \
                            ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \
                            (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \
                              ((tpcb)->unsent->len >= (tpcb)->mss))) \
                            ) ? 1 : 0)
while (seg != NULL && ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) 
{
    /* Stop sending if the nagle algorithm would prevent it
     * Don't stop:
     * - if tcp_write had a memory error before (prevent delayed ACK timeout) or
     * - if FIN was already enqueued for this PCB (SYN is always alone in a segment -
     *   either seg->next != NULL or pcb->unacked == NULL;
     *   RST is no sent using tcp_write/tcp_output.
     */
    if((tcp_do_output_nagle(pcb) == 0) &&((pcb->flags & (TF_NAGLEMEMERR | TF_FIN)) == 0))
    {
      break;
    }
    ......
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值