[英]zmq::message_t assign a string
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.我试图通过在发布者和订阅者之间创建一个简单的套接字通信来发送测试消息来熟悉 ZeroMQ。 However, I can't find the information I want on how to put a string inside a zmq::message_t type message.
但是,我找不到有关如何将字符串放入 zmq::message_t 类型消息的信息。 Indications pointed to the use of "std::memcpy(message.data(), ms.data(), ms.size())" which I tried.
迹象表明我尝试过使用“std::memcpy(message.data(), ms.data(), ms.size())”。 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?
但是,通过使用 Watchs 调试编码,我看到消息在执行后仍然为空: WATCH IMAGE并且当我使用 cout 打印出来时它也是空的: Cmd是否有另一种方法可以将字符串分配给 zmq:: message_t 消息还是这里有其他问题?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.