自定义 srv 消息
string name
---
int32 age
bool sex
修改 CMakeLists.txt
add_service_files(
FILES
stu.srv
)
generate_messages(
DEPENDENCIES
std_msgs
std_srvs
)
代码示例
服务端
#include <ros/ros.h>
#include <iostream>
#include <string>
#include "ros_learning/stu.h"
using namespace std;
bool stu_cb(ros_learning::stu::Request &request, ros_learning::stu::Response &response)
{
string input_name(request.name);
cout << input_name << endl;
response.age = 20;
response.sex = true;
return true;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "service");
ros::NodeHandle nh;
ros::ServiceServer service = nh.advertiseService("look_up_stu", stu_cb);
ros::spin();
}
客户端
#include <ros/ros.h>
#include <iostream>
#include <string>
#include "ros_learning/stu.h"
using namespace std;
int main(int argc, char** argv)
{
ros::init(argc, argv, "client");
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<ros_learning::stu>("look_up_stu");
ros_learning::stu srv;
string inputName;
while(ros::ok())
{
cin >> inputName;
srv.request.name = inputName;
if (!inputName.compare("exit"))
return 0;
if (client.call(srv))
{
cout << "name: " << srv.request.name << endl;
cout << "age: " << srv.response.age << endl;
cout << "sex: " << srv.response.sex << endl;
}
}
return 0;
}