-
Notifications
You must be signed in to change notification settings - Fork 5
example: pubsub
The Publisher / Subscriber pattern is implemented using the classes Publisher and Subscriber.
A Publisher simply sends out messages to all Subscribers (if any) that are listening to its ip address and port.
Here is an example of a Publisher for messages of type simple_msgs::Point, it will publish 10 times to any listeners on port 5555.
int main() {
simple_msgs::Point my_point{1.0, 2.0, 3.0};
simple::Publisher<simple_msgs::Point> publisher{"tcp://*:5555"};
for (auto i = 0; i < 10; ++i) {
publisher.publish(my_point);
}
}
The construction of a Publisher requires to give a string as parameter. That is identical to the interface used by ZeroMQ. In this case we use:
tcp://*:5555
Which means:
- Use
tcp://
as protocol. - Send messages to Subscribers connect from
*
any IP address. - Use the port
5555
.
You can change this parameter accordingly to your setup.
A Subscriber listens to messages sent by a Publisher on the given ip address and port.
Every message that arrives will be handled (asynchronously) by a given callback function. The function could do anything you need, in this example it just prints out the content of the message.
void example_callback(const simple_msgs::Point& p)
{
std::cout << p << std::endl;
}
int main()
{
simple::Subscriber<simple_msgs::Point> subscriber{"tcp://127.0.0.1:5555", example_callback};
}
To construct a Subscriber we used a string and the callback function. In this case we used:
tcp://127.0.0.1:5555
Which means:
- Use
tcp://
as protocol. - Connect to a Publisher on the IP:
127.0.0.1
(localhost). - Connect to a Publisher listening on port
5555
.
You can change this parameter accordingly to your setup.
The callback function:
in this small example is just a global function, but it can be anything that binds to an std::function
, that is a global function, a lamba function, a class member function, etc.
For example, if you want to pass a class member function you would need to write something similar to:
class MyClass {
MyClass(const std::string& address) subscriber_{address, std::bind(&MyClass::memberCallback, this, std::placeholders::_1)} {}
void memberCallback(const simple_msgs::Point& received_point) { ... }
private:
simple::Subscriber<simple_msgs::Point> subscriber_;
};
A full example is available for a Publisher and a Subscriber.
The example will exchange PoseStamped messages over the localhost.