我是ZeroMQ的新手。
我经常使用罗斯。因此,我对ZeroMQ中的订阅者感到困惑。在ROS中,大多数情况下,订户都有一个回调函数,只要在相应的rostopic中有数据可用,就会自动调用它。
请参阅下面的代码片段,从ROS wiki借来
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
//define subscriber and callback function associated with it
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
但是,在ZeroMQ中,似乎将订阅服务器保存在一个循环中以接收数据,如下所示:
for (int update_nbr = 0; update_nbr < 100; update_nbr++)
{
zmq::message_t update;
int zipcode, temperature, relhumidity;
// receive the data
subscriber.recv(&update);
// do something with data
std::istringstream iss(static_cast<char*>(update.data()));
iss >> zipcode >> temperature >> relhumidity;
}
上面的代码是从ZeroMQ维基借来的。
在ZeroMQ中是否也存在类似于ROS订阅者的回调机制?
发布于 2017-11-22 13:55:03
不,在ZMQ中没有回调系统。您必须调用recv()
函数才能接收消息。
您可以使用recv()
实现一个状态,因为它阻止并返回状态,因此您可以在if
条件和while
循环中使用它。
我经常用这样的模式作为超时:
zmq::context_t zmq_context(1);
zmq::socket_t zmq_socket(zmq_context, ZMQ_SUB);
zmq_socket.connect("tcp://127.0.0.1:58951");
std::string TOPIC = "";
zmq_socket.setsockopt(ZMQ_SUBSCRIBE, TOPIC.c_str(), TOPIC.length()); // allow all messages
zmq_socket.setsockopt(ZMQ_RCVTIMEO, 1000); // Timeout to get out of the while loop since recv is blocking
while(run) {
zmq::message_t msg;
int rc = zmq_socket.recv(&msg); // Is blocking until you receive a message
if(rc) {
// You received a message : your data is in msg
// Do stuff here : call your function with the parameters received from zmq
}
}
// Clean up your socket and context here
zmq_socket.setsockopt(ZMQ_LINGER, linger);
zmq_socket.close();
zmq_context.close();
https://stackoverflow.com/questions/47436219
复制相似问题