本文主要来源于:http://wiki.ros.org/ROS/Tutorials/WritingServiceClient%28c%2B%2B%29
- 写一个服务节点。
在创建消息和服务中,我们创建了一个消息AddTwoInts.srv,为实现节点功能,我们还需要编写相应代码。- 代码
在beginner_tutorials包中创建add_two_ints_server.cpp,并输入如下内容(中文注释即为说明):
#include "ros/ros.h" #include "beginner_tutorials/AddTwoInts.h"//服务头文件 bool add(beginner_tutorials::AddTwoInts::Request &req,//Request,作为输入 beginner_tutorials::AddTwoInts::Response &res)//Response,作为输出 { 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; }
- 客户端(Client)节点
代码如下(解释见中文注释)
#include "ros/ros.h" #include "beginner_tutorials/AddTwoInts.h" #include <cstdlib> 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<beginner_tutorials::AddTwoInts>("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; }
- 编译运行代码
在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)
然后运行catkin_make进行编译
使用roscore开启中心节点。
运行rosrun begginner_tutorials add_two_ints_server
启动服务节点。
运行rosrun beginner_tutorials add_two_ints_client 1 3
启动客户端节点,并传入参数
会出现:server节点会出现:
功能正确。
- 代码