Two ways of using TCP to handle sticky packets in online games

    As a connection-oriented, reliable, byte stream-based transport layer network communication protocol, TCP is widely used. Since it is a network protocol based on byte stream, we use TCP protocol for network communication, and the bottom layer will split and combine the sent data, so we generally encounter problems of sticky packets and half packets. Generally, in order to solve the sticky package problem, there are two ways to solve the sticky package and half package problem:

  1. Encapsulate the sent data into packets, just like the TCP protocol with a header.
  2. Use separators, add separators to the end of the data when sending data.

 

     The first method deals with sticky packets. You can add a 2-byte packet header to the header of the data to be sent to store the length of the data packet, and add a byte at the end of the packet to verify the data. The check value is equal to the final value of the bitwise XOR of each byte of the cyclic data.

     In general online game servers, such as mobile games, the first method will be used to deal with the sticky packet problem. The sticky packet problem will be considered when designing the protocol. Each protocol contains a protocol header and a protocol body. When designing the protocol header, we need to consider the sticky packet problem, and the protocol body is the data we want to send.

Protocol header:

struct protocol_head_t
{
   unsigned short tag;  // 0xFBFC 先导码标志消息起始
   unsigned short len;  // 数据包的长度,用来处理TCP粘包
   unsigned char  tp; // 标志协议体格式,json协议格式、Protocol Buffer协议格式等等
   unsigned short  msg_id; // 协议号用于区分协议数据,根据协议号解析数据
}__attribute__((packed));//取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,GCC特有的语法。

     The second way is to add a separator. Generally, \r\n is used as the separator, because the http request uses \r\n as the separator. The websocket protocol is used in some games. Websocket is different from the general http protocol, it is a long connection, which can realize the communication between the web and the server. In the H5 standard, the websocket protocol is implemented at the bottom level, so \r\n is used as the separator in H5 web games, WeChat games, and Douyin games, and the server side implements websocket communication.

    When we deal with the sticky packet problem, we can use it as a reference to choose an appropriate way to deal with the TCP sticky packet and half-packet problem, and design the protocol for network communication according to the actual situation

Guess you like

Origin blog.csdn.net/qq_19825249/article/details/108453972
Recommended