1

我在按字节读取 stream_socket_client 时遇到了一个奇怪的问题,我从 JAVA 发送响应,它看起来像这样:

this.writeInt(output,target.getServiceId().getBytes().length);                    
output.write(target.getServiceId().getBytes();                    
this.writeInt(output, bufret.length);
output.write(bufret);

target.getServiceId() 返回一个整数,bufret 是字符串。

在 PHP 中,我通过fread()函数读取它。

它看起来像这样:

$length = fread ($this->client, 4);     
$length = $this->getInt($length);
$serviceId = fread ($this->client, $length);
$length = fread ($this->client, 4);             
$length= $this->getInt($length);
$bufret = $this->getBufret($length);    

我将 4 个字节读入长度,因为它是整数,所以 4 个字节。我将字节解析为 int 的函数如下所示:

function getInt($length){
        $dlugosc = unpack("C*", $length);
        return ($length[1]<<24) + ($length[2]<<16) + ($length[3]<<8) + $length[4];
    }

我认为在这种情况下,功能如何工作并不重要getBufret(),但我也可以展示它

function getTresc($length){
        $count = 0;
        $bufret="";
        if($length>8192){
            $end = $length%8192;
            while($count <= $length){
                $bufret.= fread($this->client, 8192);       
                $count += 8192;
            }
        } else {
            $end = $length;
        }
        if($end >0){
            $bufret.= fread($this->client, $end);
        }
        return $bufret;
    }

所以,问题是,读写是循环的,所以流就像这样 length(integer)bufret(string)length(integer)bufret(string)length(integer)bufret(string)

在括号中,我写了一种数据。在读取时第一次执行循环时一切都很好(因为写入正常)但是当我serviceId从这 4 个字节中读取第二次长度的 a 时,我得到了String(1),但是当我跳过接下来的 4 个字节时,我可以继续读取我的字符串. utf-8 中这些“不可读”的 4 个字节如下所示:

[NULL][NULL][NULL][SO]

我实际上失去了理智,因为我不知道什么是错的,我应该做什么。

感谢帮助。问候。

4

1 回答 1

0

它可以帮助您将数据转换为您期望的类型。在我的特殊情况下,我使用网络套接字。也许这样的实现会解决你的问题。我听了数据,直到我得到一个特定的数据类型。需要注意的是,我期待的是 json。

$response = '';
$i = 0;
do {
    $http_chunk = fread($backend_socket_connect, 8192);
    $response .= $http_chunk;
    if($i === 0){
      $response = substr($response, strpos($response, '{'));
    }
    $i++;
    $result = json_decode($response,true); 
} while(!is_array($result));
于 2020-06-25T04:16:37.297 回答