service demo
原理和 topic 通信方式很像 点击打开链接,因此
1.srv :
进入 service_demo 创建 srv 文件夹,创建 Greeting.srv,将以下代码插入:
string name
int32 age
---
string feedback
这个意思是 client 将自己的名称和年龄发给 server,server 会返回一个字符串。
2.server.cpp
进入 src 文件夹,编写 server.cpp
// 加载必要文件,注意Service_demo的加载方式 # include "ros/ros.h" # include "service_demo/Greeting.h" # include "string" // 定义请求处理函数 bool handle_function(service_demo::Greeting::Request &req, service_demo::Greeting::Response &res) { // 此处我们对请求直接输出 ROS_INFO("Request from %s with age %d ", req.name.c_str(), req.age); // 返回一个反馈,将response设置为"..." res.feedback = "Hi " + req.name + ". I'm server!"; return true; } int main(int argc, char **argv) { // 初始化节点,命名为"greetings_server" ros::init(argc, argv, "greetings_server"); // 定义service的server端,service名称为“greetings”,收到request请求之后>传递给handle_function进行处理 ros::NodeHandle nh; ros::ServiceServer service = nh.advertiseService("greetings", handle_function); ros::spin(); return 0; }
3.client.cpp
# include "ros/ros.h" # include "service_demo/Greeting.h" int main(int argc, char **argv) { // 初始化,节点命名为"greetings_client" ros::init(argc, argv, "greetings_client"); // 定义service客户端,service名字为“greetings”,service类型为Service_demo ros::NodeHandle nh; ros::ServiceClient client = nh.serviceClient<service_demo::Greeting>("greetings"); // 实例化srv,设置其request消息的内容,这里request包含两个变量,name和age,见Greeting.srv service_demo::Greeting srv; srv.request.name = "HAN"; srv.request.age = 20; if (client.call(srv)) { // 注意我们的response部分中的内容只包含一个变量response,另,注>意将其转变成字符串 ROS_INFO("Response from server: %s", srv.response.feedback.c_str()); } else { ROS_ERROR("Failed to call service Service_demo"); return 1; } return 0; }
4.CMakeLists.txt & package.xml
5.编译运行
先运行 server ,再运行 client ,结果就不展示了。