Processing socket data with leading length value

This is the next question about how to handle prefixes received from a network socket. I am trying to do the following:

  • Read the first 4 bytes (which is the $ prefix and represents the length of the message)
  • Check if the $ prefix is ​​really 4 bytes in size and if it's an integer
  • Read the full $ message using the length from the $ prefix
  • Check if the message is really $ prefix bytes in size.

So far I have 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 perform these checks?

A small note: all data sent via a network socket connection is in UTF8, little-endian

+4
source share
1 answer

You can check the length of the resulting binary string 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 is a 32-bit length. Unpack as such (with the same format specifier that you use when packing it), then select the message and use strlen again to check 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 } 
+4
source

Source: https://habr.com/ru/post/1401876/


All Articles