Ask questions:

If the client continuously sends data packets to the server, the two data packets received by the server will be stuck together. This is the problem of packet sticking and packet unpacking commonly encountered in TCP.

Forms of sticking and unpacking:

Now suppose that the client sends two consecutive packets to the server, represented by packet1 and packet2, then the data received by the server can be divided into three types, which are listed as follows:

  1. The receiving end receives two packets normally. No packet unpacking or sticking occurs.

  1. The receiving end receives only one packet: Because TCP does not lose packets, this packet contains information about two packets sent by the sender. This phenomenon is called sticky packets. This situation is difficult to handle because the receiver does not know the boundary between the two packets.

  1. The receiver normally receives two redundant or incomplete packets: The receiver receives two packets, but the two packets are either incomplete or there is one extra packet. This situation is called unpacking and sticky packets. These two cases, without special treatment, are equally difficult to deal with on the receiving end.

Common reasons for sticking and unpacking:

There are many reasons for TCP sticky or unpacked packets. Here are the common ones:

  • Packet unpacking occurs when the data to be sent is larger than the remaining space of the TCP send buffer.
  • If the data to be sent is larger than MSS (maximum packet length), TCP unpacks the data before transmission.
  • The size of the data to be sent is smaller than the size of the TCP send buffer. TCP sends the data that has been written into the buffer for several times. Packet sticking occurs.
  • The application layer at the receiving end does not read the data in the receiving buffer in time, and sticky packets occur.

Solutions to sticking and unpacking problems:

Through the above analysis, we know the cause of sticking or unpacking, so how to solve this problem? The key to solve the problem is how to add boundary information to each packet. The commonly used methods are as follows:

  • The sender adds a header to each packet, and the header should contain at least the length of the packet. In this way, after receiving data, the receiver can know the actual length of each packet by reading the length field in the header.
  • The sender encapsulates each packet into a fixed length (if not, it can be filled by padding zeros), so that the receiver automatically splits each packet by reading a fixed length of data from the receive buffer.
  • A boundary can be set between packets, such as a special symbol, so that the receiver can separate different packets through this boundary.

Post a big guy Chen (mudo network library writers) solution: (a kind of automatic reflex message type Google Protobuf network transmission scheme) blog.csdn.net/solstice/ar…