14.10 Controlling Data Transfer Timeout


You want the socket to time out after a certain time if the reading operation is blocked.

Technique

For high-level sockets, use the socket_set_timeout() function:

 <?php $sock = fsockopen("www.slashdot.org", 80, $errstr, $errno, 30); if(!$sock) {     dir($errstr); } socket_set_timeout($sock, 60); fwrite($sock,"GET / HTTP/1.0\n\n"); $res = fread($sock, 2000); $status = socket_get_status($sock); if ($status['timed_out']) {     print "Timeout\n";     fclose($sock); } else    print $res; ?> 

Comments

If you use blocking sockets but still want the read operation to time out after a certain period, you should make use of socket_set_timeout() function. It takes the socket descriptor as the first parameter, and number of seconds and microseconds specifying the timeout as the second and third parameters.

After the socket read operation exits, the way to find out whether timeout occurred is to call the socket_get_status() function and check the 'timed_out' entry in the array it returns. If the 'timed_out' entry is true, the socket read timed out; otherwise , the operation was completed successfully. See the next section for more information about socket_get_status() .



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net