Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending sockets data with a leading length value

I want to send JSON messages from a PHP script to a C# app over a network connection using PHP Sockets.

Usually, for binary protocols, the first 4 bytes of every message must be an integer which represents the length (how many bytes) of the message.

In C# I prefix every message with an integer that tells the length of the message as follow:

byte[] msgBytes = UTF8Encoding.UTF8.GetBytes("A JSON msg");            
byte[] prefixBytes = BitConverter.GetBytes(msgBytes.Length);
byte[] msgToSend = new byte[prefixBytes.Length + msgBytes.Length];
Buffer.BlockCopy(prefixBytes, 0, msgToSend, 0, prefixBytes.Length);
Buffer.BlockCopy(msgBytes, 0, msgToSend, prefixBytes.Length, msgBytes.Length);

As I understand, in PHP the function socket_send only accept strings. So, how can I do the same prefixing in PHP 5.x?

Update: I posted a follow-up question on how to process such prefixed data when received from a network socket.

like image 390
Mike Avatar asked Mar 16 '12 18:03

Mike


1 Answers

In PHP strings are binary.

So you need to encode the integer length value as the binary representation of an unsigned integer as a 4-char (4 Octets; 32 bits) string. See pack:

# choose the right format according to your byte-order needs:

l   signed long (always 32 bit, machine byte order)
L   unsigned long (always 32 bit, machine byte order)
N   unsigned long (always 32 bit, big endian byte order)
V   unsigned long (always 32 bit, little endian byte order)

$string = pack('l', $length);
like image 76
hakre Avatar answered Oct 18 '22 15:10

hakre