public function receive($length = self::DEFAULT_RECEIVE_LENGTH)
{
$buffer = '';
$metadata['unread_bytes'] = 0;
do {
// feof means socket has been closed
// also, sometimes in long running processes the system seems to kill the underlying socket
if (!$this->socket || feof($this->socket)) {
$this->disconnect();
return $buffer;
}
$result = fread($this->socket, $length);
// fread FALSE means socket has been closed
if ($result === false) {
$this->disconnect();
return $buffer;
}
$buffer .= $result;
// feof means socket has been closed
if (feof($this->socket)) {
$this->disconnect();
return $buffer;
}
$continue = false;
if ($this->firstRead == true && strlen($result) == 1) {
// Workaround Chrome behavior (still needed?)
$continue = true;
}
$this->firstRead = false;
if (strlen($result) == $length) {
$continue = true;
}
// Continue if more data to be read
$metadata = stream_get_meta_data($this->socket);
if ($metadata && isset($metadata['unread_bytes']) && $metadata['unread_bytes']) {
$continue = true;
$length = $metadata['unread_bytes'];
}
} while ($continue);
return $buffer;
}