01-ROS入门-08 ROS服务通信

1. 编写服务器程序

cd ~/joey_ws/src/joey_example1
vim ~/joey_ws/src/joey_example1/src/sum_server.cpp


<sum_server.cpp>

#include "ros/ros.h"
#include "joey_example1/sum.h"

bool add(joey_example1::sum::Request  &req,
         joey_example1::sum::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, "sum_server");
  ros::NodeHandle n;

  ros::ServiceServer service = n.advertiseService("sum", add);
  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;
}

2. 编写客户端程序

cd ~/joey_ws/src/joey_example1
vim ~/joey_ws/src/joey_example1/src/sum_client.cpp


<sum_client.cpp>

#include "ros/ros.h"
rinclude "joey_example1/sum.h"
#include <cstdlib>

int main(int argc, char **argv)
{
  ros::init(argc, argv, "sum_client");
  if (argc != 3)
  {
    ROS_INFO("usage: sum_client X Y");
    return 1;
  }

  ros::NodeHandle n;
  ros::ServiceClient client = n.serviceClient<joey_example1::sum>("sum");
  joey_example1::sum srv;
  srv.request.a = atoll(argv[1]);
  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 sum");
    return 1;
  }

  return 0;
}

3. 更改CMakelist.txt文件

cd ~/joey_ws/src/joey_example1
vim ~/joey_ws/src/joey_example1/CMakelist.txt


<CMakelist>

add_executable(sum_server src/sum_server.cpp)
target_link_libraries(sum_server ${catkin_LIBRARIES})
add_dependencies(sum_server joey_example1_gencpp)

add_executable(sum_client src/sum_client.cpp)
target_link_libraries(sum_client ${catkin_LIBRARIES})
add_dependencies(sum_client joey_example1_gencpp)

4. 编译执行文件

cd ~/joey_ws/
catkin_make

5. 执行服务器-客户端程序

source ~/joey_ws/devel/setup.bash
roscore
rosrun joey_example1 sum_server
rosrun joey_example1 sum_client 4 6

推荐阅读更多精彩内容