I am trying to familiarize myself with ZeroMQ by creating a simple socket communication betwenn a publisher and a subscriber to send a test message. However, I can't find the information I want on how to put a string inside a zmq::message_t type message. Indications pointed to the use of "std::memcpy(message.data(), ms.data(), ms.size())" which I tried. However, by debuging the coding using Watchs, I see that the message is still empty after execution: WATCH IMAGE and it is also empty when I print it out using a cout: Cmd Is there another way to assign a string to a zmq::message_t message or is there something else wrong here?
My entire code is:
int main()
{
zmq::context_t context(1);
zmq::socket_t pub(context, ZMQ_PUB);
pub.bind("tcp://*:5555");
std::cout << "Pub Connected" << std::endl;
zmq::socket_t sub(context, ZMQ_SUB);
sub.connect("tcp://localhost:5555");
std::cout << "Sub Connected" << std::endl;
std::stringstream s;
s << "Hello World";
auto ms = s.str();
zmq::message_t message(ms.size());
memcpy(message.data(), ms.c_str(), ms.length());
pub.send(message, zmq::send_flags::none);
std::cout << "message: " << message << std::endl;
zmq_sleep(1);
sub.set(zmq::sockopt::subscribe, "Hello World");
zmq::message_t rx_msg;
sub.recv(rx_msg,zmq::recv_flags::none);
std::string rx_str;
rx_str.assign(static_cast<char*>(rx_msg.data()), rx_msg.size());
std::cout << "Message: " << rx_str << "received!" << std::endl;
}
CodePudding user response:
There is a constructor for zmq::message_t
that has the signature (docs)
message_t(const void *data_, size_t size)
so you could use this like
zmq::message_t message(static_cast<void*>(ms.data()), ms.size());