douxu9707 2013-04-27 22:06
浏览 156

使用stream_socket_client和php字符串发送二进制消息

I am using php to connect to a socket server to send binary data - ie not standard ascii (or printable) strings. For example a message may contain ascii 0 or any number from 0 - 255.

I have functions for example like this:

function append_uint16($str, $num) {
   $str += chr($num % 256);
   $num /= 256;
   $str += chr($num);
   return $str;
}

It is called like this:

$msg = "\xA7\xA7";
$payload_size = 9 + 1 + strlen($param1) + 1 + strlen($param2);
$msg += append_uint16($msg, $payload_size);

Then I am sending to a socket server like this:

function send_msg($host, $port, $msg) {
  $fp = stream_socket_client("tcp://" . $host . ":" . $port, $errno, $errstr, 30);
  if (!$fp) {
       echo "$errstr ($errno)<br />
";
  } else {
      fwrite($fp, $msg);
  }
}

But the messages are not correctly formed. I suspect that my string processing is not quite correct. Or maybe I can't use strings in php in this way? Any ideas?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog