简单的服务端
这部分我们来写一个服务端节点和客户端节点,同样的是用CPP。我们先来创建一个新的服务端节点add_two_ints_server,想要让他接收两个整数返回他们的和。
$ cd catkin_ws/src/beginner_tutorials
$ gedit add_two_ints_server.cpp
粘贴下面的内容:
#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"
bool add(beginner_tutorials::AddTwoInts::Request &req,
beginner_tutorials::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::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();