In TCP/IP, no matter how much data is sent, always add a protocol header before the data. At the same time, the other party receives the data and also needs to send an ACK to confirm. To make full use of network bandwidth, TCP always wants to send big data as much as possible. (MSS parameters are set for a connection. Therefore, TCP/IP needs to be able to send data with MSS data blocks each time ).
The Nagle algorithm is used to send as much data as possible to avoid the Network Flooding with many small data blocks.
The basic definition of the Nagle algorithm is any time, and there can be only one unconfirmed small segment at most. The so-called "small segment" refers to a data block smaller than the MSS size. The so-called "unconfirmed" refers to a data block sent out, no ack sent by the other party is received to confirm that the data has been received.
For example, in an experiment in a previous blog, the client initially calls the socket write operation to write an int-type data (called block A) to the network, because the connection is idle at this time (that is, there are no unconfirmed segments), the int type data will be sent to the server immediately, and then, the client also calls the write operation to write '\ r \ n' (Block B). At this time, the ACK of Block A does not return, so we can think that there is an unconfirmed small segment, so block B is not sent immediately, and it is sent until the ACK of Block A is received (about 40 ms later. The entire process:
The problem is hidden here, that is, why does the ACK of Block A receive data 40 ms later? This is because TCP/IP not only has the Nagle algorithm, but also has an ACK delay mechanism. After the server receives the data, it does not immediately send ACK to the client. Instead, it delays ack sending for a period of time (assumed as t ), it hopes that the server will send the response data to the client within t time, so that ack can be sent together with the response data, just as the response data volume carries ack. In my previous time, t was about 40 ms. This explains why '\ r \ n' (Block B) is always issued 40 ms after block.
If you think the Nagle algorithm is too messy, you can disable it by setting tcp_nodelay. Of course, a more reasonable solution is to use a big data write operation instead of multiple small data write operations.