Service
Service is a request/response communication model: the client sends a structured request (request) to exactly one server providing that service, the server finishes processing and returns the corresponding result (response).
Different from topic in that there is a clear start and end point for a call — more like calling a function from another process than broadcasting a data stream. A service can only be processed by one server at a time (not "broadcast" like a topic), and the client will wait until it receives a response before continuing.
When to use service, when to use topic?
| Topic | Service | |
|---|---|---|
| type | continuous, one-way stream | One question, one answer |
| Example | 10 Hz sensor data | "Reset counter", "sum of two numbers" |
| Sender knows the result? | No | Yes, when the server replies |
Watch step by step
Client sends a and b. The server adds and returns sum. Let's follow each step as it happens.
Client wait while server processes. If the server works for a long time (a few seconds), use action instead of service, which will be learned in Module 12.
Example in project: add_two_ints
In package ros2_basics there is a server that adds two numbers and a client calls it:
# Register the service "add_two_ints" with the handler function
self.service = self.create_service(AddTwoInts, "add_two_ints", self.on_add_two_ints)
# Processing function: receive request, fill in response, return
def on_add_two_ints(self, request, response):
response.sum = request.a + request.b
return response
Need 2 terminals (already source install/setup.bash, see Module 0) — server keeps terminal running forever, does not exit automatically:
# Terminal 1 — keep running; do not close
ros2 run ros2_basics add_two_ints_server
# Terminal 2
ros2 run ros2_basics add_two_ints_client 3 5 # result: 8
Try it
# Terminal 2 — the server in Terminal 1 is still running
ros2 service list
ros2 service type /add_two_ints
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 3, b: 5}"