美文网首页程序员
用C++编写一个简单的服务端和客户端

用C++编写一个简单的服务端和客户端

作者: 网路元素 | 来源:发表于2019-10-09 00:20 被阅读0次

    1.首先执行roscd beginner_tutorials命令,然后创建src/add_two_ints_server.cpp服务端源码,内容如下:

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

      booladd(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 twoints.");
          ros::spin();
          return 0;
      }

    2.接下来创建src/add_two_ints_client.cpp客户端程序,源码如下:

      #include "ros/ros.h"
      #include"beginner_tutorials/AddTwoInts.h"
      #include <cstdlib>

      int main(int argc, char **argv)
      {
          ros::init(argc, argv,"add_two_ints_client");
          if (argc != 3)
          {
              ROS_INFO("Usage: add_two_ints_clientX Y");
              return 1;
          }
          ros::NodeHandle n;
          ros::ServiceClient client =n.serviceClient("add_two_ints");
          beginner_tutorials::AddTwoInts srv;
          srv.request.a = atoll(argv[1]);
          srv.request.b = atoll(argv[2]);
          if (client.call(srv))
          {
              ROS_INFO("Sum: %ld", (longint)srv.response.sum);
          }
          else
          {
              ROS_ERROR("Failed to callservice add_two_ints");
              return 1;
          }
          return 0;
      }

    3.接下来修改CMakeLists.txt文件,在文件尾部添加如下内容:

      add_executable(add_two_ints_serversrc/add_two_ints_server.cpp)
      target_link_libraries(add_two_ints_server${catkin_LIBRARIES})
      add_dependencies(add_two_ints_serverbeginner_tutorials_gencpp)

      add_executable(add_two_ints_clientsrc/add_two_ints_client.cpp)
      target_link_libraries(add_two_ints_client${catkin_LIBRARIES})
      add_dependencies(add_two_ints_clientbeginner_tutorials_gencpp)

    4.编译运行

      cd ~/ros/catkin_ws
      catkin_make

      执行如下命令运行服务端:

      rosrun beginner_tutorials add_two_ints_server

      执行后会有如下提示:

      [ INFO] [1497789377.150363403]: Ready to addtwo ints.

      接下来执行客户端:

      rosrun beginner_tutorialsadd_two_ints_client  1 3

      会有如下提示:

      [ INFO] [1497789453.191450800]: Sum: 4

      而刚才服务端会有如下提示:

      [ INFO] [1497789453.191038638]: request: x=1,y=3
      [ INFO] [1497789453.191116375]: sending backresponse: [4]

    参考网址:http://wiki.ros.org/ROS/Tutorials/WritingServiceClient%28c%2B%2B%29

    相关文章

      网友评论

        本文标题:用C++编写一个简单的服务端和客户端

        本文链接:https://www.haomeiwen.com/subject/ejhfpctx.html