When data is transmitted, we often use the TCP protocol to transmit it. When we use a TCP long connection to transmit different types of data, the problem of sticking and unpacking occurs.
The production of sticky packs: Sticky packets may occur on the server or in the client, when submitting data to TCP, TCP does not send this data immediately, but waits a short time to see if there are any data to send during the waiting period, and if so, send the two pieces of data out at once, causing the sticky package The other end after receiving the database, put into the buffer, if the message was not taken away from the buffer in time, the next time in the data can be taken out of the case of multiple packets, resulting in sticky packet phenomenon.
The generation of packet breakage: When using TCP to transmit data, it is possible that the data is too large, so that the sender buffer cannot be sent once, causing the other end only to receive incomplete data, so wait for the data to be fully received and then parse the data.
TCP sticky package, half packet processing mode: The first is the use of separators, the use of special separators as a packet of the end of the second is to the specific location of each packet (such as Baotou two bytes) plus packet length information, the other end of the data packet based on the length of the interception of a specific length of data analysis, Assuming that the data length of the header information is Infolen, and the packets received are of a true length of truelen, there are several situations:
1, Infolen>truelen, half a bag.
2, Infolen<truelen, sticky bag.
3, Infolen=truelen, normal.
while (1) {
var Packlen = _.unpack (' Packlen ', Tcpbuffer.slice (0, 2));
len = Packlen.len;
Console.log (' Pack len------: ' + len ');
Console.log (' True len------: ' + tcpbuffer.length);
if (Len > Tcpbuffer.length) {
Writelog (' info ', ' code:2011 half pack ', NULL);
Return
}
Tcp_pack_unpack (Tcpbuffer.slice (0, Len));
if (len = = tcpbuffer.length) {//pack end
Tcpbuffer = new Buffer (0);
Return
else {//pack not end
Writelog (' info ', ' code:2100 more packs in one buffer ', null);
Tcpbuffer = Tcpbuffer.slice (len);
}
}