The following is my code. I wish fread can return when there don't have data to read after some seconds. I called stream_set_timeout. But it don't work. And I called stream_get_meta_data too. It don't give my need yet. I am connecting chat.facebook.com.
$fp = fsockopen($server, 8888, $errno, $errstr);
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
fwrite($fp, $xml);
stream_set_timeout($fp, 5);
$str = fread($fp,8192);//This code will hang when there don't have data to read.开发者_Python百科
If you'd read the manual for stream_set_timeout()
you'd know that the only thing stream_set_timeout()
does in case of timeout is setting of 'timed_out' key of the array returned by stream_get_meta_data()
to true.
stream_set_timeout($fp, 5);
// set stream into non-blocking mode
stream_set_blocking($fp, false);
$break_counter = 0;
$result = '';
$info = stream_get_meta_data($fp);
while (!$info['timed_out'] && !feof($fp)) {
$str = @fgets($fp, 1160);
if ($str) {
$result .= $str;
} else {
$break_counter += 1;
if ($break_counter > 100) {
break;
}
// 10000*100 microseconds gives you one second
usleep(10000);
}
$info = stream_get_meta_data($fp);
}
精彩评论