Here’s a clear example using turtlesim in ROS 2 that demonstrates both Publish/Subscribe and Service/Clientcommunication, along with an explanation of their differences.
1. Publish/Subscribe Example with Turtlesim
- Publisher Node: Sends velocity commands to move the turtle.
- Subscriber Node: (turtlesim itself) Listens for these commands and moves the turtle accordingly.
Command-line demonstration:
`bash*# Start turtlesim*
ros2 run turtlesim turtlesim_node
# Publish a velocity command to move the turtle forward
ros2 topic pub /turtle1/cmd_vel geometry_msgs/msg/Twist "{linear: {x: 2.0, y: 0.0, z: 0.0}, angular: {x: 0.0, y: 0.0, z: 0.0}}"`
- Here, you (or a node) are the publisher, sending messages to the
/turtle1/cmd_vel topic.
- The turtlesim node is the subscriber, receiving and acting on those messages.
- Key characteristic: This is a continuous, one-way communication. The publisher keeps sending messages, and the subscriber keeps listening and acting on them6.
2. Service/Client Example with Turtlesim
- Service Server: turtlesim provides a service, such as
/spawn (to create a new turtle) or /clear (to clear the screen).
- Service Client: You (or a node) send a request to the service and wait for a response.
Command-line demonstration:
bash*# Call the /spawn service to create a new turtle at (x=2, y=2, theta=0.2)* ros2 service call /spawn turtlesim/srv/Spawn "{x: 2, y: 2, theta: 0.2, name: ''}"
- Here, you are the client, making a request to the
/spawn service.
- The turtlesim node is the service server, which processes the request and sends back a response (the name of the new turtle).
- Key characteristic: This is a two-way, one-time communication. The client sends a request, the server processes it, sends a response, and the interaction ends134.
Comparison Table
| Pattern |
Example Command/Node |
Direction |
Continuous? |
Use Case |
| Publish/Subscribe |
ros2 topic pub /turtle1/cmd_vel ... |
One-way |
Yes |
Move the turtle continuously |
| Service/Client |
ros2 service call /spawn ... |
Two-way (request/response) |
No |
Spawn a new turtle (on demand) |
Summary of Differences