Sending Socket Data Using Lead Length

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

Typically for binary protocols, the first 4 bytes of each message should be an integer that represents the length (how many bytes) of the message.

In C #, I prefix each message with an integer that reports the length of the message as follows:

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 it, in PHP, the socket_send function only accepts strings. So how can I do the same prefix in PHP 5.x?

Update: I sent the following question about how to process such prefix data when it is received from a network socket.

+4
source share
2 answers

In PHP, strings are binary.

So, you need to encode the integer-length value as a binary representation of the integer character n un as a 4-char string (4 octets, 32 bits). 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); 
+5
source

I think you could use pack () to convert the number of bytes to a binary string. When you send your data over the network, you probably need to convert using the "N" format (unsigned long, always 32-bit, large ordinal byte order).

Here is an example:

 $s="Hello World"; $length=pack("N",strlen($s)); socket_send($sock,$length.$s,4+strlen($s)); 
+5
source

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


All Articles