TCP sticking/unpacking

        Readers familiar with TCP programming may know that whether it is a server or a client, when we read or send messages, we need to consider the underlying sticking/unpacking mechanism of TCP. The following is a detailed introduction to the TCP sticking/unpacking problem and the solution.

        TCP is a "stream" protocol. The so-called stream is a series of data without boundaries. You can think of the flowing water in a river. They are connected together, and there is no dividing line between them.

question:

                                

        TCP sticky packet: When the socket reads, it reads the contents of two or more data packets in the actual sense, and processes it as one data packet at the same time.

        TCP unpacking: When a socket is read, a data packet is not read in its entirety, but only a part of it is read.

Solution:

        There are four general ways to deal with the sticking/unpacking problem:

         1. The data segment is fixed-length processing, and the vacancies with insufficient digits are filled.

         2. Message header + message body. The message header generally contains the length of the message body, message type and other information, and the message body is the actual data body.

         3. Special characters (such as carriage return) are used as the end of the message data to realize the segmentation of the message data.

         4. The complex application layer protocol, which is used relatively rarely, couples the network layer and the application layer.

        The purpose of the above four methods is to accurately separate the data in the stream for further analysis and processing. In the custom protocol, the second method is used more, because it can better meet the needs of customized protocol development, such as self-defined protocol. When defining the Netty protocol, you can put specific data packets into the message body, and put other variables in the message header as needed (such as: message type, which can specifically correspond to the heartbeat message, client request message, service for maintaining long netty links) side processing result messages, etc.).

Guess you like

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