我在按字节读取 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]
我实际上失去了理智,因为我不知道什么是错的,我应该做什么。
感谢帮助。问候。