rabbitmq-c send nlohmann json



想要通过RabbitMQ-C发送图像,但图像文件太大。接收器无法检索图像。所以,我将图像转换为base64,然后将其放入JSON中。

const char *msg;

FILE *image1;
if (image1 = fopen(path, "rb")) {
fseek(image1, 0, SEEK_END); //used to move file pointer to a specific position
// if fseek(0 success, return 0; not successful, return non-zero value
//SEEK_END: end of file

length = ftell(image1); //ftell(): used to get total size of file after moving the file pointer at the end of the file
sprintf(tmp, "size of file: %d  bytes", length);
//convert image to base64
std::string line;
std::ifstream myfile;
myfile.open(path, std::ifstream::binary);
std::vector<char> data((std::istreambuf_iterator<char>(myfile)), std::istreambuf_iterator<char>() );
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
std::string code = base64_encode((unsigned char*)&data[0], (unsigned int)data.size());

//convert std::string to const char 
const char* base64_Image = code.c_str();


json j ;


j.push_back("Title");
j.push_back("content");
j.push_back(base64_Image);

std::string sa = j.dump();
msg = sa.c_str();       //convert std::string to const char*

}
else {
return;
}

使用RabbitMQ-C将消息(msg(发送到接收器,但失败[错误指向此处]

是const char*不能使用amqp_cstring_bytes(msg(转换为amqp_bytes_t吗??

respo = amqp_basic_publish(conn, 1, amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key),0, 0, NULL, amqp_cstring_bytes(msg));

并得到这个错误


If there is a handler for this exception, the program may be safely continued.```

Anyone know how to send image as JSON using RabbitMQ-C & C++ ?

amqp_cstring_bytes需要一个C字符串,该字符串通常以NUL字节结尾。你的PNG文件几乎可以保证包含一个NUL字节,所以这就解释了为什么你的消息在中途被切断了。

至于粘贴中的代码:sa.c_str()返回的指针只有在sa处于活动状态且未修改时才有效。一旦您退出包含sa定义的块,变量就死了。

相反,使用amqp_bytes_alloc获得一个适当大小的缓冲区,并返回:

amqp_bytes_t bytes = amqp_bytes_malloc(sa.length());
strncpy((char *)bytes.bytes, sa.c_str(), sa.length());

然后将CCD_ 6对象传递给CCD_。做完后别忘了ampqp_bytes_free

最新更新