Rosanswers logo

Hi, I have a limited knowledge in C++ so that feel a difficulty in combining a subscriber and a publisher in one C++ file. Based on the tutorial, http://www.ros.org/wiki/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29 , could anybody give some directions on making one C++ file which includes a subscriber and a publisher ?

Originally posted by maruchi on ROS Answers with karma: 157 on 2011-12-11

Post score: 2


2 Answers 2


Rosanswers logo

Hi, Like there is 1 subscriber and 1 publisher in the tutorial. Try to write 2 chatters. i.e each chatter should be able to listen and also talk. In the subscriber of the tutorial add a publisher with different topic. Here is example code. I haven't executed it but it should be simple enough to understand.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>

void chatterCallback(const std_msgs::String::ConstPtr& msg)
  ROS_INFO("I heard: [%s]", msg->data.c_str());

int main(int argc, char **argv)

  ros::init(argc, argv, "listener");   
  ros::NodeHandle n;   
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("different_chatter", 1000);

  ros::Rate loop_rate(10);   
  int count = 0;
  while (ros::ok())
    std_msgs::String msg;

    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());





  return 0;

Now you can write the second chatter listening to "different_chatter" and publishing to "chatter" topics. Hope this helps,


Originally posted by karthik with karma: 2831 on 2011-12-11

This answer was ACCEPTED on the original site

Post score: 11

Original comments

Comment by maruchi on 2011-12-11:
Karthik, thanks for your help. If it is possible, could you put some comment to my question on here, http://answers.ros.org/question/3274/how-to-add-a-subscriber-in-keyboard-teleop


Rosanswers logo

here is good solusion. http://answers.ros.org/question/59725/publishing-to-a-topic-via-subscriber-callback-function/?answer=59738#post-id-59738

Originally posted by sxin with karma: 11 on 2016-01-21

This answer was NOT ACCEPTED on the original site

Post score: 1


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.