14.8 Nonblocking Sockets


You don't want your sockets to wait around forever trying to connect to a given server.

Technique

If you are using the high-level socket functions, use the socket_set_blocking() function:

 <?php $fp = fsockopen('www.webtechniques.com', 80, $errno, $errstr, 30); if (!$fp) {     die(sprintf('Error [%d]: %s',                 $errno, $errstr)); } socket_set_blocking($fp, false); fwrite($fp, "GET / HTTP/1.0\r\n\r\n"); while ($line = fgets($fp, 1024)) {     print $line; } fclose($fp); 

Or, if you are using the lower-level socket functions, you can use the set_nonblock() function:

 <?php $sock = socket(AF_INET, SOCK_STREAM, 0); if ($sock < 0)     die(strerror($sock)); if (($ret = set_nonblock($sock)) < 0)     die(strerror($ret)); if (($ret = connect($sock, $addr, $port)) < 0)     die(strerror($ret)); if (($ret = write($sock, $data, $len)) < 0)     print strerror($ret); while (read($sock, $buf, $buflen) < 0)     print $buf; ?> 

Comments

If you do not want your sockets to block, or wait for data if data is not available, use the appropriate function to set blocking to zero. When you set blocking to zero, the socket doesn't wait for data, but instead immediately returns if it cannot access data from the stream.



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