新建消息类型
流程点这里
添加头文件
修改配置文件 修改CmakeList.txt
服务端实现
#include "ros/ros.h"
#include "pub_sub_server/add.h"
//数据处理函数
bool donum(pub_sub_server::add::Request &request,pub_sub_server::add::Response &response)
{
//对于参数赋值
int num1=request.num1;
int num2=request.num2;
ROS_INFO("num1=%d,num2=%d",num1,num2);
response.sum=num1+num2;
ROS_INFO("sum=%d",response.sum);
return true;
}
int main(int argc, char *argv[])
{
//防止中文乱码
setlocale(LC_ALL,"");
//初始化ros
ros::init(argc,argv,"hei");
//创建句柄
ros::NodeHandle nh;
//发布服务端
ros::ServiceServer server=nh.advertiseService("add",donum);
//输出日志
ROS_INFO("server_start");
//回调函数
ros::spin();
return 0;
}
客户端实现
#include "ros/ros.h"
#include "pub_sub_server/add.h"
//数据处理函数
int main(int argc, char *argv[])
{
//防止中文乱码
setlocale(LC_ALL,"");
//初始化ros
ros::init(argc,argv,"shui");
//创建句柄
ros::NodeHandle nh;
//创建客户端
ros::ServiceClient client=nh.serviceClient<pub_sub_server::add>("add");
//数据处理
pub_sub_server::add ai;
ai.request.num1=100;
ai.request.num2=200;
bool flag=client.call(ai);
if (flag)
{
ROS_INFO("响应的结果为:%d",ai.response.sum);
}else
{
ROS_INFO("响应失败!");
}
return 0;
}
修改配置文件
注意修改 add_dependencies