-
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 pointed to 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.
A full example is available for a Publisher and a Subscriber.
The example will exchange PoseStamped messages across the localhost.