sticky package problem

Streaming Protocols and Sticky Packets

TCP is a streaming protocol

  • TCP is based on byte stream transmission. It can only maintain how much is sent and how much is confirmed. It does not maintain the boundary between messages, so it may cause sticky packets.
  • The solution to the sticky packet problem is to maintain message boundaries at the application layer.

write picture description here
The figure reflects the transmission of packets in the network. We cannot predict what the original boundaries of the data received in the TCP receive buffer will be.

cause

write picture description here

TCP is a stream of bytes, unbounded. For the client and server, a read operation does not guarantee that the data can be read. The number of received packets is also indeterminate.

Analysis of the causes of the sticky packet problem:
1. The SQ_SNDBUF socket itself has buffers (send buffer, receive buffer)
2. The mss size limit of the tcp transmission end
3. The link layer also has a MTU size limit, if the data packet is larger than >MTU is fragmented at the IP layer, resulting in message fragmentation.
4. The flow control and congestion control of tcp may also lead to sticky packets
5, tcp delay sending mechanism, etc.
Conclusion : The tcp/ip protocol does not deal with the sticky packet problem at the transport layer.

solution

Essentially: it is to maintain the boundary between messages and messages at the application layer

two ways

  • Add \n at the end of the package
    • \nAs the boundary of the agreement
    • recv()use MSG_PEEKlogo
  • Baotou plus bag body length
    • When sending a message, the length of the first four bytes (converted to network byte order) + the packet body
    • When receiving a message, read the first four bytes first to find the length; read the data according to the length

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324702846&siteId=291194637