ROS-客户端,服务端

add_two_ints_server

#include "ros/ros.h"
#include "bingda_practices/AddTwoInts.h"


bool add(bingda_practices::AddTwoInts::Request &req,
         bingda_practices::AddTwoInts::Response &res)//&req,&res均为client里的srv
         {
                 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;

}

add_two_ints_client

#include "ros/ros.h"
#include "bingda_practices/AddTwoInts.h"//srv文件头文件

int main(int argc, char **argv)
{
        ros::init(argc, argv, "add_two_ints_client");
        if (argc != 3)//3的原因:x,y,并+1
        {
                ROS_INFO("usage: add_two_ints_client X Y");
                return 1;
        }
        ros::NodeHandle n;
        ros::ServiceClient client = n.serviceClient<bingda_practices::AddTwoInts>("add_two_ints");
        bingda_practices::AddTwoInts srv;
        srv.request.a = atoll(argv[1]);//atoll参数类型转换
        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;
        

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ROS系统中,服务端客户端的概念可以理解为提供服务和请求服务的节点。服务端节点提供服务,客户端节点请求服务,它们之间通过消息传递进行通信。 下面是一个简单的服务端客户端的Python编程示例: 服务端代码: ```python #!/usr/bin/env python import rospy from std_srvs.srv import Empty def my_service_callback(request): print("My service has been called!") #实现服务功能 return [] rospy.init_node('my_service_server') my_service = rospy.Service('/my_service', Empty, my_service_callback) print("My service is ready to receive requests!") rospy.spin() #保持节点运行状态 ``` 客户端代码: ```python #!/usr/bin/env python import rospy from std_srvs.srv import Empty rospy.init_node('my_service_client') rospy.wait_for_service('/my_service') #等待服务启动 my_service_proxy = rospy.ServiceProxy('/my_service', Empty) response = my_service_proxy() #发送请求 ``` 上述代码中,服务端使用`rospy.Service`函数创建一个服务节点,指定服务名称为`/my_service`,服务类型为`Empty`,并指定回调函数`my_service_callback`用于处理服务请求。 客户端使用`rospy.ServiceProxy`函数创建一个服务代理,指定服务名称为`/my_service`,服务类型为`Empty`,并通过调用`my_service_proxy()`方法发送请求,最终获得服务的响应结果。 需要注意的是,服务端客户端的节点名称应该相互独立,避免节点名称冲突。同时,在ROS系统中,服务端客户端节点的启动顺序也很重要,需要确保服务端节点在客户端节点之前启动。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值