简介
1.话题的缺点。
在ros通讯时,话题会按时持续的发送数据,这导致在我们不需要这些数据时发送一些无用数据,而且还消耗电脑资源。
2.服务器的优点
在客户端访问主机前,主机一直在静默,知道客户端请求才发送消息。
实例
1.1创建功能包
//创建example_cpp功能包。(存放实例)
ros2 pkg create example_cpp --build-type ament_cmake --dependencies rclcpp --license Apache-2.0
1.2在src中创建客户端
创建service_client_01.cpp,代码如下还有注释
#include "rclcpp/rclcpp.hpp"
#include "example_interfaces/srv/add_two_ints.hpp"
class ServiceClient01 : public rclcpp::Node
{
public:
// 构造函数,有一个参数为节点名称
ServiceClient01(std::string name) : Node(name)
{
RCLCPP_INFO(this->get_logger(), "节点已启动:%s.", name.c_str());
// 创建客户端
client_ = this->create_client<example_interfaces::srv::AddTwoInts>("add_two_ints_srv");
}
void send_request(int a, int b)
{
// 打印日志,输出计算a+b
RCLCPP_INFO(this->get_logger(), "计算%d+%d", a, b);
while (!client_->wait_for_service(std::chrono::seconds(1))) // 使用while循环等待服务端上线,每秒检测一次
{
if (!rclcpp::ok()) // 如果rclcpp的状态被打断,则打印错误日志并返回
{
RCLCPP_ERROR(this->get