Skip to content

Instantly share code, notes, and snippets.

@nikiink
Last active August 29, 2015 14:22
Show Gist options
  • Save nikiink/cc6212a3ca50f4c80da2 to your computer and use it in GitHub Desktop.
Save nikiink/cc6212a3ca50f4c80da2 to your computer and use it in GitHub Desktop.
<?php
function waitUntilPortIsListening($host, $port, $options = array('usleep' => 300000, 'limit' => 20)) {
$limit = array_key_exists('limit',$options)?$options['limit']:20;
$retries = 0;
while (true) {
$connection = @fsockopen($host, $port);
if (is_resource($connection)) {
echo "is listening\n";
fclose($connection);
break;
} else {
echo "is not responding\n";
}
usleep(array_key_exists('usleep',$options)?$options['usleep']:300000); //default 300 ms
if ($retries >= $limit) {
throw new Exception("Number of retries exceeded limit, port still not responding");
}
$retries++;
}
}
@nikiink
Copy link
Author

nikiink commented Jun 1, 2015

This method waits until a port on an host is listening. The usleep options is the microseconds to wait before retry. The limit is the number of retries to guess until throwing an exception because the port is still not responding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment