How to write byte by byte to socket in PHP?

蹲街弑〆低调 提交于 2019-12-10 13:54:45

问题


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.



来源:https://stackoverflow.com/questions/2473203/how-to-write-byte-by-byte-to-socket-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!