(2)send数据细节

来源:互联网 发布:狸窝音频转换器mac版 编辑:程序博客网 时间:2024/06/07 13:56

Nagle’s algorithm

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, this can be written in pseudocode as

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(就是这个地方,要等前面的已发送的包全部被ack才继续放送这个小于MSS的包)    else      send data immediately    end if  end ifend if

This algorithm interacts badly with TCP delayed acknowledgments, a feature introduced into TCP at roughly the same time in the early 1980s, but by a different group. With both algorithms enabled, applications that do two successive writes to a TCP connection, followed by a read that will not be fulfilled until after the data from the second write has reached the destination, experience a constant delay of up to 500 milliseconds, the “ACK delay”. For this reason, TCP implementations usually provide applications with an interface to disable the Nagle algorithm. This is typically called the TCP_NODELAY option.

开启 TCP_NODELAY

简单地说,这个选项的作用就是禁用 Nagle’s Algorithm,禁止后当然就不会有 它引起的一系列问题了。在 UNIX C 里使用 setsockopt 可以做到:
void _set_tcp_nodelay(int fd) {
int enable = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&enable, sizeof(enable));
}