ROS之服务中的Server和Client

服务:

一个srv文件描述一项服务。它包含两个部分:请求和响应
服务(services)是节点之间通讯的另一种方式。服务允许节点发送请求(request) 并获得一个响应(response)

上一篇博客讲过了,如何新建工作空间和功能包,不在赘述了,在learning_communication功能包中

1、创建服务(server)节点

在功能包下的src文件下,即learning_communication/src创建服务(server)节点文件:server.cpp   内容如下:

//Add Two_Ints Server
#include "ros/ros.h" #include "learning_communication/AddTwoInts.h" // service回调函数,输入参数req,输出参数res bool add(learning_communication::AddTwoInts::Request &req, learning_communication::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节点初始化 ros::init(argc, argv, "add_two_ints_server"); // 创建节点句柄 ros::NodeHandle n; // 创建一个名为add_two_ints的server,注册回调函数add() ros::ServiceServer service = n.advertiseService("add_two_ints", add); // 循环等待回调函数 ROS_INFO("Ready to add two ints."); ros::spin(); return 0; }

2、创建客户端(client)节点

在功能包下的src文件下,即learning_communication/src创建客户端(client)节点文件:client.cpp   内容如下:

//  Add TwoInts Client

#include <cstdlib>
#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"

int main(int argc, char **argv)
{
    // ROS节点初始化
    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;

    // 创建一个client,请求add_two_int service
    // service消息类型是learning_communication::AddTwoInts
    ros::ServiceClient client = n.serviceClient<learning_communication::AddTwoInts>("add_two_ints");

    // 创建learning_communication::AddTwoInts类型的service消息
    learning_communication::AddTwoInts srv;
    srv.request.a = atoll(argv[1]);
    srv.request.b = atoll(argv[2]);

    // 发布service请求,等待加法运算的应答结果
    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;
}

创建一个srv头文件:

int64 a
int64 b
---
int64 sum

3、编译

返回工作空间根目录进行编译:

cd ~/ROS_Learning
catkin_make

编译完成后运行  

roscore
rosrun learning_communication server   #需开启新终端
rosrun learning_communication client  #需开启新终端

运行结果如图所示:

 

原文地址:https://www.cnblogs.com/qilai/p/13983304.html