C++实现Client端

Client创建流程

1. 创建节点

1
2
ros::init(argc, argv, nodeName);
ros::NodeHandle node;

2. 通过Node创建Client端

1
ros::ServiceClient &&client = node.serviceClient<roscpp_tutorials::TwoInts>(serviceName);

3. 调用Service

1
2
3
4
5
6
7
8
9
// 创建Service
roscpp_tutorials::TwoInts service;
service.request.a = 10;
service.request.b = 5;
//发送请求
client.call(service);

//获取响应结果
ROS_INFO_STREAM("响应结果: " << service.response.sum);

完整代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include "ros/ros.h"

#include "roscpp_tutorials/TwoInts.h"

using namespace std;

int main(int argc, char **argv) {
  //初始化节点
  string nodeName = "my_service_client";
  ros::init(argc, argv, nodeName);
  //创建节点
  ros::NodeHandle node;

  //创建Service Client
  string serviceName = "my_service";
  ros::ServiceClient client = node.serviceClient<roscpp_tutorials::TwoInts>(serviceName);

  // 创建Service
  roscpp_tutorials::TwoInts service;
  service.request.a = 10;
  service.request.b = 5;
  //发送请求
  client.call(service);

  //获取响应结果
  ROS_INFO_STREAM("响应结果: " << service.response.sum);

  //阻塞
  ros::spin();
  return 0;
}

调试Client端

通过已有的server来调试client

1
rosrun demo_service client