Sending sockets data with a leading length value

倾然丶 夕夏残阳落幕 提交于 2019-12-05 13:13:05

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);

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

Here's an example:

$s="Hello World";
$length=pack("N",strlen($s));
socket_send($sock,$length.$s,4+strlen($s));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!