Search code examples
c++rabbitmqamqp

AMQP-CPP RabbitMQ receiving extra sign, message.body() by one greater than message.size()


When I receive a message, I get the message content with message.body(), but always with an extra character at the end. The content of message.body() is always one greater than message.size(). The extra character is'Î' and has the ASCII code Decimal 206, I don't understand why this character is included. I always have to cut off the message around this sign, which need not be.

My Callback for receiving messages:

void Communicator_RabbitMQ::MessageCB(const AMQP::Message &message, uint64_t deliveryTag, bool redelivered)
{
    cout << "Message received: (" << message.body() << ") , " <<  "Body Size: " << message.bodySize() << endl;

}

Example:

Published the following payload via the RabbitMQ Management UI: : "12345"

Output from Callback:

Message received: (12345�) , Body Size: 5

Debugger:

*(message.body() + 5)   0xce 'Î'    const char

When I consum the message with the RabbitMQ Management UI, I receive the following Payload :

Payload 5 bytes 12345 Encoding: string


Solution

  • Please consider that

    message.body()
    

    returns a pointer to a NOT-null-terminated string. You should use message.bodySize() to check the actual length.

    Example 1: (copy content)

    void Communicator_RabbitMQ::MessageCB(const AMQP::Message &message, uint64_t deliveryTag, bool redelivered)
    {
        cout << "Message received: (" << std::string(message.body(), message.body() + message.bodySize()) << ") , " << "Body Size: " << message.bodySize() << endl;
    }
    

    Example 2: (using c++17's string_view)

    void Communicator_RabbitMQ::MessageCB(const AMQP::Message &message, uint64_t deliveryTag, bool redelivered)
    {
        cout << "Message received: (" << std::string_view(message.body(), message.bodySize()) << ") , " << "Body Size: " << message.bodySize() << endl;
    }