Ask Your Question

A question about Service and Client

asked 2021-02-17 09:12:31 -0500

sunpansiyu gravatar image

I followed the tutorials ( I found that in my client cpp file there's a code line

 beginner_tutorials::AddTwoInts srv


if (

So I think the server function received data from client by “srv”.

But in my server cpp file, it says

ros::ServiceServer service = n.advertiseService("add_two_ints", add);


`bool add(beginner_tutorials::AddTwoInts::Request  &req,
       beginner_tutorials::AddTwoInts::Response &res)`{}

so it looks like server function received two variables(one for request one for response).

My question is that if I wrrite it

`bool add(beginner_tutorials::AddTwoInts srv)`{}

will it work?

Thank you.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2021-02-18 09:07:21 -0500

JackB gravatar image

The line

beginner_tutorials::AddTwoInts srv;

Is actually declaring a service message, which is defined here as:

int64 a
int64 b
int64 sum

A service message, by convention is split into a "request" and "response" part. For this message "a" and "b" are part of the request and "sum" is part of the response. To access these variables in code you can do like:

 beginner_tutorials::AddTwoInts srv;
 srv.request.a = 5;
 srv.request.b = 4;

Your service, defined by:

ros::ServiceServer service = n.advertiseService("add_two_ints", add);

Has a "callback" function, here named "add" whose signature by design explicitly names the the request AND response parts. That is why "add" takes two arguments.

bool add(beginner_tutorials::AddTwoInts::Request  &req,
               beginner_tutorials::AddTwoInts::Response &res)

For practical purposes however all you have to do to call the service is declare the client:

ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints");

And then call it with the SINGLE argument, srv:

And after the call, it it was successful, you can access the result like this:


Does that help answer your question at all?

Cheers, JB

edit flag offensive delete link more


@sunpansiyu any update on this?

JackB gravatar image JackB  ( 2021-02-24 07:42:12 -0500 )edit

I am so sorry for my late response! Thank you for your answer, it helps me a lot!

sunpansiyu gravatar image sunpansiyu  ( 2021-03-21 02:22:34 -0500 )edit

I understand it now ,thank you!

sunpansiyu gravatar image sunpansiyu  ( 2021-03-21 02:23:13 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2021-02-17 09:12:31 -0500

Seen: 70 times

Last updated: Feb 18 '21