服务中的Server和Cliet
编写AddTwoInts.srv文件
int64 a
int64 b
---
int64 sum
编写Server代码
#include <ros/ros.h>
#include <example2/AddTwoInts.h>////beginner_tutorials/AddTwoInts.h是由编译系统自动根据我们先前创建的srv文件生成的对应该srv文件的头文件。
bool add(example2::AddTwoInts::Request &req,
example2::AddTwoInts::Response &res)
{
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, "example2_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("AddTwoInts", add);
ROS_INFO("Ready to add two ints.");
ros::spin();
return 0;
}
编写Client代码
#include<cstdlib>
#include "ros/ros.h"
#include<example2/AddTwoInts.h>
int main(int argc, char ** argv)
{
ros::init(argc, argv, "example2_client");
if(argc != 3)
{
ROS_INFO("usage: add_two_ints_client X Y");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<example2::AddTwoInts>("AddTwoInts");
example2::AddTwoInts srv;
srv.request.a = atoll(argv[1]);
srv.request.b = atoll(argv[2]);
if(client.call(srv))
{
ROS_INFO("Sum: %ld", (long int)srv.response.sum);
}
else
{
ROS_INFO("Failed to call service add_two_ints");
return 1;
}
return 0;
}
运行代码
$ roscore
$ rosrun example2 server
$ rosrun example2 client 4 5
来源:https://blog.csdn.net/weixin_42361804/article/details/98884260