代码之家  ›  专栏  ›  技术社区  ›  ravi

ZeroMQ中的子订阅者是否具有与ROS中相同的“回调”机制?

  •  2
  • ravi  · 技术社区  · 7 年前

    我是ZeroMQ的新手。

    我使用 ROS 频繁地因此,我对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 wiki .

    1 回复  |  直到 7 年前
        1
  •  1
  •   user3666197    7 年前

    不,ZMQ中没有回调系统。你必须打电话 recv() 函数以接收消息。

    您可以使用 recv() if 条件和a 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();