使用前导长度值处理套接字数据 [英] Process socket data with a leading length value

查看:90
本文介绍了使用前导长度值处理套接字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关如何操作的后续问题处理从网络套接字接收的前缀消息.我想做的是:

This is a follow-up question about how to process prefixed messages received from a network socket. What I try to do is:

  1. 读取前4个字节(即$ prefix,代表消息的长度)
  2. 检查$ prefix的大小是否真的为4个字节,并且是否为整数
  3. 使用$ prefix中的长度阅读完整的$ message
  4. 检查消息是否确实具有$ prefix字节大小

到目前为止,我有以下两行代码:

So far I've the following two lines of code:

    $prefix = socket_read($socket, 4, PHP_BINARY_READ); //No 1.
    //No 2: how to do the checks?
    $message = socket_read($socket, $prefix, PHP_BINARY_READ); //No 3.
    //No 4: how to do the checks?

如何进行上述检查?

一个小小的注意事项:通过网络套接字连接发送的所有数据都在UTF8中,即Little-endian

A little side note: all data sent through the network socket connection is in UTF8, little-endian

推荐答案

您只需使用

You can validate the length of the binary string you have received by simply using strlen:

$prefix = socket_read($socket, 4, PHP_BINARY_READ);
if (strlen($prefix) != 4) {
    // not 4 bytes long
}

根据您先前的问题,此二进制字符串表示32位长. 解压缩这样(使用与打包相同的格式说明符) ,然后获取消息并再次使用strlen验证长度:

According to your previous question, this binary string represents a 32-bit long. Unpack it as such (with the same format specifier you use when pack-ing it), then fetch the message and use strlen again to validate the length:

$length = current(unpack('l', $prefix));
$message = socket_read($socket, $length, PHP_BINARY_READ);
if (strlen($message) != $length) {
    // $message not the size of $length
}

这篇关于使用前导长度值处理套接字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆