1

I have a weird problem with reading stream_socket_client by bytes, I send response from JAVA, it looks like this:

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

target.getServiceId() returns a integer, and bufret is string.

In PHP i read it by a fread() function.

It looks like this:

$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);    

I read 4 bytes into length because is integer so 4 bytes. My function to parse bytes to int looks like this:

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

I think in that case its not matter how getBufret() function works, but i can show it as well

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;
    }

So, the problem is, reading and writing is in loop, so the stream goes like this length(integer)bufret(string)length(integer)bufret(string)length(integer)bufret(string)

in brackets i wrote a type of data. Everything is fine in first execution of the loop while reading (because writing is going ok) but when I read for second time length of a serviceId from these 4 bytes I get String(1), but when I skip next 4 bytes, I can continue to read my string. These "unreadable" 4 bytes in utf-8 looks like these:

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

I actually lost my mind, because I have no idea what is wrong, and what I supposed to do.

Thanks for help. Regards.

rdabrowski
  • 189
  • 1
  • 6
  • 16

1 Answers1

0

It may help you to cast the data to the type you expect. In my particular case, I worked with web sockets. Perhaps such an implementation will solve your problem.I listened to the data until I get a specific data type. It is important to note that I was expecting 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));
Hackimov
  • 92
  • 6