Current Location: Home> Latest Articles> Pack() application example in Socket communication

Pack() application example in Socket communication

M66 2025-06-03

When conducting Socket communication in PHP, we often encounter situations where we need to package (encapsulate) and unpack the data, especially when we need to transfer data in a specific binary format. The pack() function is the weapon to solve this problem. This article will combine a simple example to explain the specific usage of the pack() function in Socket communication.


What is the pack() function?

pack() is a built-in function of PHP, which can package data into binary strings according to the specified format. This way, the processed data is more compact and convenient to transmit on the network.

The basic syntax is:

 string pack ( string $format , mixed $args [, mixed $... ] )
  • $format is a format string that defines packaging rules, such as integer, character, floating point, etc.

  • The subsequent parameters are data in the corresponding format.


Why does Socket communication require pack()?

During Socket communication, data is sent in a byte stream. The endianness of different machines may be different, and sending text or normal data directly may cause the receiver to parse errors.

Using pack() can:

  • Encode data in a fixed format to ensure that the formats of the sending and receiving ends are consistent.

  • Handle endianness issues (big endian, little endian).

  • Generate binary data with fixed length for easy transmission and parsing.


Explain the application of pack() in Socket communication with an example

Suppose we want to send a data packet through TCP Socket, the format is as follows:

Fields type illustrate
Package length unsigned short (2 bytes) Package length, excluding the package length field itself
Command number unsigned short (2 bytes) Command ID
data String Specific content

Send code example

 <?php
// Simulate sent data
$command = 1001;
$data = "Hello, socket communication!";

// Calculate the data length
$dataLen = strlen($data);

// The length of the package is the command number length + Data length (2 + $dataLen)
$packetLen = 2 + $dataLen;

// use pack Package length and command number(use网络字节序,Big endian)
$header = pack('n', $packetLen) . pack('n', $command);

// Splicing complete package
$packet = $header . $data;

// Assume that it has been established socket connect,socket_write Send data
// socket_write($socket, $packet, strlen($packet));

echo "发送的二进制Data length: " . strlen($packet) . "\n";
echo "Binary data16Category representation: " . bin2hex($packet) . "\n";
?>

Analysis instructions

  • pack('n', $packetLen) means packing $packetLen in an unsigned short integer (2 bytes) and network endianness (big endian).

  • pack('n', $command) Similarly, pack the command number.

  • After splicing, the package follows the data content.

Receiver parsing example

After receiving the data, you can parse it like this:

 <?php
// Assumptions $recvData Yes from socket Read binary data
// For example: $recvData = socket_read($socket, 1024);

// First parse the package length and command number
$header = substr($recvData, 0, 4);
list($packetLen, $command) = array_values(unpack('npacketLen/command', $header));

// Extract the data content
$data = substr($recvData, 4, $packetLen - 2);

echo "Package length: $packetLen\n";
echo "Command number: $command\n";
echo "Data content: $data\n";
?>

summary

  • The pack() function is a powerful tool for binary data packaging and is suitable for various network protocols and binary file operations.

  • In Socket communication, rational use of pack() can ensure consistent data format and stable communication.

  • Combined with the unpack() function, binary data parsing can be easily performed.

  • Pay special attention to the endianness issue. Network communication generally adopts network endianness (big endianness), and it is most common to use the 'n' format to package short integers.

If you are doing network communication based on binary protocols, it is highly recommended to practice pack() and unpack() more, which will greatly improve your ability to process packets.