TCP connection sends data only one way does not receive

491 views Asked by At

I have fought enough with this: I am trying to write a TCP client code and this code has to send a data to a server and and get a response. The client code is as follows:

<?php
$str3 = "Test Data";
echo $str3;
$fp = stream_socket_client("tcp://192.168.1.26:12000", $errno, $errstr, 30);
if (!$fp) 
{
    echo "$errstr ($errno)<br />\n";
    echo "Some problem! </br>";
} 

else 
{   
    fwrite($fp,$str3);
    $str = "";

    while ($str == "")
    {
       $str = fgets($fp, 1024);
    }

    fclose($fp);
    echo $str;
}
?> 

The remote host receives the data and responds back too. Unfortunately, I dont get the data in $str. I do not control the remote host and I can only see that it has received data and generated response. Can you suggest, where exactly am I going wrong?

1

There are 1 answers

1
sarnold On BEST ANSWER

You may wish to try a more idiomatic read loop; I've stolen this code from http://www.php.net/manual/en/function.fgets.php:

while (($buffer = fgets($fp, 4096)) !== false) {
    echo $buffer;
}
if (!feof($fp)) {
    echo "Error: unexpected fgets() fail\n";
}
fclose($fp);