Fsockopen connection does not close before timeout

Background : I have to create a simple site that accepts incoming XML and sends XML to the server through a socket connection and, in turn, displays the XML sent from the server. Easy peasy.

Problem : I had no problems using fsockopen () to connect to the server and send XML. Reading XML from the server was a completely new problem. Normal

while (!feof($fp)) {    
    echo fgets($fp);
}

did not perform the trick, since the server returns one XML line and only one XML line (without length information, eof, eol, etc.). Thus, he will wait until the timeout is reached, display the received XML and a timeout error. My problem is like this dinosaur .

In a nutshell, I want to read the XML on the socket and close it as soon as no more data is sent (do not wait for a timeout). Setting the timeout to a low value was also not viable, as the server response can vary from 2 to 30 seconds.

Solution : After the fighting all day, I decided to share the next solution to this problem (to criticize).

$fp = fsockopen("123.456.789.1", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)";
} else {
    $wait = true;    
    $out = '<samplexml><item>something</item></samplexml>';

    // [1] disable blocking
    stream_set_blocking($fp, 0);
    fwrite($fp, $out);

    while (!feof($fp)) {
        $r = fgets($fp);
        echo $r;
        if (!strcmp($r, "")){                
            if (!$wait) {
                // [2] has recieved data on this socket before
                break;
            }
        } else {
            $wait = false;
        }
    }
    fclose($fp);
}

Turns out my main problem was blocking. So, firstly, [1] I had to disable stream_set_blocking so that fgets () could constantly check if new data appeared. If not disabled, fgets () will get the XML from the server, and then the loop will get stuck in the second attempt, as it will wait for more data (which it never will).

, , , - fgets(), - fgets(), ).

, stackoverflow.

+5
3

:

  • -, strcmp($r, "") . , . , fgets . , FALSE. , FALSE . .
  • -, , . , fgets false, , . , , , .
  • , . .

stream_select. - , -.

+2

fread() . , , , , XML , -. :

while(true) {
    $char = fread($fp, 1);
    $xml .= $char;
    if (is_complete($xml)) {
         break;
    }
}
0

I am using a socket. I send the xml string and get the xml string too. When the server sends me a string '</response>', I have to close the socket. Below you can find my code if this can help someone:

            stream_set_blocking($fp, 0);
            fwrite($fp, $in);
            $result = '';

            while (!feof($fp)) {
                $r = fgets($fp);
                $result .= $r;
                //echo $r;
                if (strstr($r, "</response>") != null)
                    break;
            }
            fclose($fp);
0
source

All Articles