1.首先执行roscd beginner_tutorials命令,然后创建src/add_two_ints_server.cpp服务端源码,内容如下:
#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"
bool add(beginner_tutorials::AddTwoInts::Request &req,
beginner_tutorials::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, "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;
}
2.接下来创建src/add_two_ints_client.cpp客户端程序,源码如下:
#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"
#include
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_two_ints_client");
if (argc != 3)
{
ROS_INFO("Usage: add_two_ints_client X Y");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient("add_two_ints");
beginner_tutorials::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_ERROR("Failed to call service add_two_ints");
return 1;
}
return 0;
}
3.接下来修改CMakeLists.txt文件,在文件尾部添加如下内容:
add_executable(add_two_ints_server src/add_two_ints_server.cpp)
target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
add_dependencies(add_two_ints_server beginner_tutorials_gencpp)
add_executable(add_two_ints_client src/add_two_ints_client.cpp)
target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
add_dependencies(add_two_ints_client beginner_tutorials_gencpp)
4.编译运行
cd ~/ros/catkin_ws
catkin_make
执行如下命令运行服务端:
rosrun beginner_tutorials add_two_ints_server
执行后会有如下提示:
[ INFO] [1497789377.150363403]: Ready to add two ints.
接下来执行客户端:
rosrun beginner_tutorials add_two_ints_client 1 3
会有如下提示:
[ INFO] [1497789453.191450800]: Sum: 4
而刚才服务端会有如下提示:
[ INFO] [1497789453.191038638]: request: x=1, y=3
[ INFO] [1497789453.191116375]: sending back response: [4]
5.参考网址
http://wiki.ros.org/ROS/Tutorials/WritingServiceClient%28c%2B%2B%29
网友评论