Пример #1
0
    /**
     * Reads in a frame from the socket or returns false.
     *
     * @return \Zend\Queue\Stomp\StompFrame|false
     * @throws \Zend\Queue\Exception
     */
    public function read()
    {
        $this->ping();

        $response = '';
        // as per protocol COMMAND is 1st \n terminated then headers also \n terminated
        // COMMAND and header block are seperated by a blank line.

        // read command and headers
        while (($line = @fgets($this->_socket)) !== false) {
            $response .= $line;
            if (rtrim($line) === '') break;
        }

        $this->_checkSocketReadTimeout();

        // to differenciate between a byte message and
        // non-byte message, check content-length header
        $headers = Frame::extractHeaders($response);
        if (!isset($headers[Frame::CONTENT_LENGTH])) {
            // read till we hit the end of frame marker
            do {
                $chunk = @fgets($this->_socket);
                if ( $chunk === false || strlen($chunk) === 0) {
                    $this->_checkSocketReadTimeout();
                    break;
                }
                if (substr($chunk, -2) === Frame::END_OF_FRAME) {
                    // add the chunk above to the result before returning
                    $response .= $chunk;
                    break;
                }
                $response .= $chunk;
            } while (feof($this->_socket) === false);
        } else {
            // we have a content-length header set
            $contentLength = $headers[Frame::CONTENT_LENGTH] + 2;
            $current_pos = ftell($this->_socket);
            $chunk = '';

            for ($read_to = $current_pos + $contentLength;
                $read_to > $current_pos;
                $current_pos = ftell($this->_socket)
            ) {
                $chunk = fread($this->_socket, $read_to - $current_pos);
                if ($chunk === false || strlen($chunk) === 0) {
                    $this->_checkSocketReadTimeout();
                    break;
                }
                $response .= $chunk;
                // Break if the connection ended prematurely
                if (feof($this->_socket)) {
                    break;
                }
            }
        }

        if ($response === '') {
            return false;
        }

        // we already have headers, prevent extracting the headers again
        $frame = $this->createFrame();
        $frame->setCommand(Frame::extractCommand($response))
              ->setHeaders($headers)
              ->setBody(Frame::extractBody($response));
        return $frame;
    }