This is a follow-up question about how to process prefixed messages received from a network socket. What I try to do is:
So far I've the following two lines of code:
$prefix = socket_read($socket, 4, PHP_BINARY_READ); //No 1.
//No 2: how to do the checks?
$message = socket_read($socket, $prefix, PHP_BINARY_READ); //No 3.
//No 4: how to do the checks?
How can I do the mentioned checks?
A little side note: all data sent through the network socket connection is in UTF8, little-endian
You can validate the length of the binary string you have received by simply using strlen
:
$prefix = socket_read($socket, 4, PHP_BINARY_READ);
if (strlen($prefix) != 4) {
// not 4 bytes long
}
According to your previous question, this binary string represents a 32-bit long. Unpack it as such (with the same format specifier you use when pack-ing it), then fetch the message and use strlen
again to validate the length:
$length = current(unpack('l', $prefix));
$message = socket_read($socket, $length, PHP_BINARY_READ);
if (strlen($message) != $length) {
// $message not the size of $length
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With