1 前提
在/catkin_ws/src/beginner_tutorials/srv 目录下创建好AddTwoInts.srv
1 int64 a
2 int64 b
3 ---
4 int64 sum
2 编写server节点
[~/catkin_ws/src/beginner_tutorials]$ vim src/add_two_ints_server.cpp
add_two_ints_server.cpp内容如下:
1 #include "ros/ros.h"
2 /* 是编译器系统自动根据用户自己创建的srv文件生成的对应头文件 */
3 #include "beginner_tutorials/AddTwoInts.h"
4
5 bool add(beginner_tutorials::AddTwoInts::Request &req,
6 beginner_tutorials::AddTwoInts::Response &res)
7 {
8 res.sum = req.a + req.b;
9 ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
10 ROS_INFO("sending back response: [%ld]", (long int)res.sum);
11 return true;
12 }
13
14
15 int main(int argc, char **argv)
16 {
17 ros::init(argc, argv, "add_two_ints_server");
18 ros::NodeHandle n;
19 /* 创建server, 并在ros内发布出来 */
20 ros::ServiceServer service = n.advertiseService("add_two_ints", add);
21 ROS_INFO("Ready to add two ints.");
22 ros::spin();
23
24 return 0;
25 }
26
3 编写client节点
[~/catkin_ws/src/beginner_tutorials]$ vim src/add_two_ints_client.cpp
add_two_ints_client.cpp内容如下:
1 #include "ros/ros.h"
2 #include "beginner_tutorials/AddTwoInts.h"
3 #include <cstdlib>
4
5
6 int main(int argc,char **argv)
7 {
8 ros::init(argc, argv, "add_two_ints_client");
9 if(argc != 3)
10 {
11 ROS_INFO("usage: add_two_ints_client");
12 return 1;
13 }
14
15 ros::NodeHandle n;
16 ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoIn ts>("add_two_ints");
17 beginner_tutorials::AddTwoInts srv;
18 srv.request.a = atoll(argv[1]);
19 srv.request.b = atoll(argv[2]);
20 if(client.call(srv))
21 {
22 ROS_INFO("Sum: %ld", (long int)srv.response.sum);
23 }
24 else
25 {
26 ROS_INFO("Failed to call service add_two_ints");
27 return 1;
28 }
29
30 return 0;
31
32
33 }
34
35
4 编译
修改CMakeLists.txt文件,在文件末尾增加
211
212 add_executable(add_two_ints_server src/add_two_ints_server.cpp)
213 target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
214 add_dependencies(add_two_ints_server beginner_tutorials_gencpp)
215
216 add_executable(add_two_ints_client src/add_two_ints_client.cpp)
217 target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
218 add_dependencies(add_two_ints_client beginner_tutorials_gencpp)
编译
[~/catkin_ws]$ catkin_make
5 验证
运行Service
rosrun beginner_tutorials add_two_ints_server
另启终端运行Client
rosrun beginner_tutorials add_two_ints_client 1 3
Service端显示:
Client端显示