I'm fetching data from a socket that pumps data at unknown intervals. There could be nothing for minutes (or even hours) and then tens of thousands of rows can be queued ready for reading.
Because I don't know what to expect, I was hoping to build something that connects for 2-5 seconds slurping in however much it can, irrespective of how much is queued up at the server end.
This is what I have at the moment.
<?php
set_time_limit(2);
ini_set('max_input_time', 2);
$timeout = 3;
$host = 'data.host.com';
$port = 6543;
$fp = fsockopen($host, $po开发者_Python百科rt, $errno, $errstr, $timeout);
stream_set_timeout($fp, 2);
if( !$fp ){
echo "Connection to '$host' failed.\n$errstr ($errno)\n";
exit;
}
while( !feof($fp) ){
$xml = trim(fgets($fp));
if(empty($xml)) continue;
echo "XML=$xml\n";
}
echo "DONE\n";
function shutdown(){
echo "SHUTDOWN!\n";
}
register_shutdown_function('shutdown');
However this never finishes at all. The while loop appears to be as infinite as one might expect (out of context). How do I put in and capture some exit/break/kill?
This may not be the best/correct way to do it, but it should work (untested)
$startTime = time();
$executionTime = 180; //180 Seconds - 2 Minutes
while( !feof($fp) ){
if ((time() - $startTime) > $executionTime) {
//If time has been longer than the execution time, break
//out of loop
break;
}
$xml = trim(fgets($fp));
if(empty($xml)) continue;
echo "XML=$xml\n";
}
I believe this is a mysql connection, if so use the default port. Restricting the socket connection is not advisable unless you can store all transaction in a temp db and push else where at the time alloted.
$start_time = time();
while( !feof($fp) ){
$xml = trim(fgets($fp));
if(empty($xml)) continue;
echo "XML=$xml\n";
if ( time() - $star_time > 320 ) break;
}
精彩评论