add_two_ints_server
#include "ros/ros.h"
#include "bingda_practices/AddTwoInts.h"
bool add(bingda_practices::AddTwoInts::Request &req,
bingda_practices::AddTwoInts::Response &res)//&req,&res均为client里的srv
{
res.sum = req.a + req.b;
ROS_INFO("request: x=%ld, y=%ld",(long int)req.a, (long int)req.b);
ROS_INFO("sending back response: [%ld]",(long int)res.sum);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_two_ints_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("add_two_ints", add);
ROS_INFO("Ready to add two ints.");
ros::spin();
return 0;
}
add_two_ints_client
#include "ros/ros.h"
#include "bingda_practices/AddTwoInts.h"//srv文件头文件
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_two_ints_client");
if (argc != 3)//3的原因:x,y,并+1
{
ROS_INFO("usage: add_two_ints_client X Y");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<bingda_practices::AddTwoInts>("add_two_ints");
bingda_practices::AddTwoInts srv;
srv.request.a = atoll(argv[1]);//atoll参数类型转换
srv.request.b = atoll(argv[2]);
if (client.call(srv))
{
ROS_INFO("Sum: %ld", (long int)srv.response.sum);
}
else{
ROS_ERROR("Failed to call service add_two_ints");
return 1;
}
return 0;
}