How to write byte by byte to socket in PHP?

2019-06-22 15:13发布

问题:

How to write byte by byte to socket in PHP?

For example how can I do something like:

socket_write($socket,$msg.14.56.255.11.7.89.152,strlen($msg)+7);

The pseudo code concatenated digits are actually bytes in dec. Hope you understand me.

回答1:

You can use the pack function to pack the data into any datatype you wish. Then send it with any of the socket functions.

$strLen = strlen($msg);

$packet = pack("a{$strLen}C7", $msg, 14, 56, 255, 11, 7, 89, 152);

$pckLen = strlen($packet);

socket_write($socket, $packet, $pckLen);


回答2:

As per http://www.php.net/manual/en/function.socket-create.php#90573

You should be able to do

socket_write($socket,"$msg\x14\x56\x255\x11\x7\x89\x152",strlen($msg)+7);


回答3:

Before PHP 6, bytes are just characters. Writing a string out is the same thing as writing an array of bytes. If those are the ascii character decimal values, you can replace your $msg... bit with:

$msg.chr(14).chr(56).chr(255).chr(11).chr(7).chr(89).chr(152)

If you could explain what you are attempting to do it will be easier for us to provide a more helpful answer, but in the meantime that accomplishes what you've described so far.