Home>Article>Backend Development> Share a php tcp packet sticking/unpacking example
This article will introduce you to an example about PHP's tcp sticking/unpacking. I hope it will be helpful to friends who need it~
In tcp long link mode, Use a fixed message header length method to unpack messages to solve the sticky problem. The fixed message header protocol
fixes the first N bytes of the message header as the message length bits. Combined with the business scenario, 2bytes or 4bytes, when reading the message, first read the message length bits, and then according to the specific message The length reads the message content. [Recommended learning:PHP video tutorial]
pack/unpack can pack values into binary/unpack binary into values. For specific modes, please refer to the detailed usage of pack/unpack. Here we choose fixed The header length is 2 bytes to represent the length of the message body. The maximum length of the message body can be represented by 2^16 - 1. If it is not enough, you can use 4 bytes.
Group package
sticky package
// send // 传输 $package 由 $foo $bar 两条消息组成 模拟粘包场景 // receiveUnpacking
The TCP scenario often encountered in daily work may be the short connection single message mode. The client closes the connection after sending a message, and the server reads EOF in a loop to get a complete message. However, if there are multiple messages in a short connection or in a long link mode, sticky packets may occur, and the client cannot confirm that the message has been read through EOL without closing the server. This requires defining protocols and unpacking.
The above is the detailed content of Share a php tcp packet sticking/unpacking example. For more information, please follow other related articles on the PHP Chinese website!