This article follows on from the previous article and shows you how to use ProtoBuf

Background: Use the ProtoBuf protocol to communicate with corporate C++ bosses

The biggest problem encountered in the process of communication with the big guy is that each other do not understand the data format and other doubts, here is also a universal data transmission process and byte stream and other content, some piecemeal, please forgive me

As an example of the next data format problem, in C++ an integer may be a signed integer or an unsigned integer. In addition, there are 16 – and 32-bit differences in data.

We know that a byte is eight bits, which is how many bits there are in binary

Now let’s talk about ProtoBuf

ProtoBuf is divided into three parts. The first part is the message content length (head), the second is the message content type (type), and the third is the message body (body).

Because protobuf is passed in as a binary package, PHP uses the pack() and unpack() functions to unpack the package and pass the data to the protobuf unpack function

Here’s an example:

A sends A protobuf package to B. A defines the first part of the package as A 4-byte (32-bit) signed integer (head) and the second part as A 2-byte (16-bit) signed integer (type). Then the third part is the body of the message, so for PHP, you need to parse the package first, unpack in PHP, and for unpack/unpack, you use the two functions unpack(), unpack($format,$args) takes two arguments, unpack($format,$args), The first parameter is the unpacking parameter, The second parameter is the binary byte streams Reference the bosses here for binary package format for correlation analysis, the use of the specific about these two functions walks bosses at https://segmentfault.com/a/1190000008305573 In the example above, unpack using unpack(). The first 4-byte 32-bit signed integer corresponds to the unpack parameter I, which is unpack('Ihead',$STR). I have defined a head after I to accept the parsed value. ['head' => XXXX, 'head' => XXXX ['head' => XXXX, 'type' => XXXX, ['head' => XXXX, 'type' => XXXX, ['head' => XXXX, 'type' => XXXX ] since we get the value in the second 2 bytes we have to carry the first 4 bytes as well, or we can use substr() to get the middle 2 bytes out to use unpack or the value in the third part can be fetched with substr since there are 6 bytes of head and type, So the body of the third part can be fetched directly with substr() substr(6, STR) and then the retrieved value will be placed inside the protobuf parsing function for the correct read and write