diff --git a/src/Client.php b/src/Client.php index 95d4b90..079254b 100644 --- a/src/Client.php +++ b/src/Client.php @@ -286,4 +286,31 @@ protected function configure(array $options): void parent::configure($options); } + + /** + * Waits for data to become available on the socket. + * + * @param float $maxSeconds the maximum amount of time to wait for data, in seconds + * + * @return ?bool Returns true if data is available, false if the wait timed out, and null on error. + */ + public function waitForData(float $maxSeconds): ?bool + { + $read = [$this->socket->getResource()]; + $write = null; + $except = null; + $seconds = (int) \floor($maxSeconds); + $microseconds = (int) (($maxSeconds - $seconds) * 1e6); + $result = \stream_select($read, $write, $except, $seconds, $microseconds); + if (false === $result) { + // An error occurred. stream_select() probably triggered an error internally. + return null; + } elseif (0 === $result) { + // Timeout occurred, no data available + return false; + } + + // Data is available + return true; + } }