Reading stream_socket_client by bytes using fread()
<p>I have a weird problem with reading stream_socket_client by bytes, I send response from JAVA, it looks like this:</p>

<pre><code>this.writeInt(output,target.getServiceId().getBytes().length);                    
output.write(target.getServiceId().getBytes();                    
this.writeInt(output, bufret.length);
output.write(bufret);
</code></pre>

<p>target.getServiceId() returns a integer, and bufret is string.</p>

<p>In PHP i read it by a <code>fread()</code> function.</p>

<p>It looks like this:</p>

<pre><code>$length = fread ($this-&gt;client, 4);     
$length = $this-&gt;getInt($length);
$serviceId = fread ($this-&gt;client, $length);
$length = fread ($this-&gt;client, 4);             
$length= $this-&gt;getInt($length);
$bufret = $this-&gt;getBufret($length);    
</code></pre>

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

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

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

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

<p>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)</p>

<p>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 <code>serviceId</code> from these 4 bytes I get <code>String(1)</code>, but when I skip next 4 bytes, I can continue to read my string. These "unreadable" 4 bytes in utf-8 looks like these:</p>

<pre><code>[NULL][NULL][NULL][SO]
</code></pre>

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

<p>Thanks for help.
Regards.</p>