ros创建一个服务和客户端,完成随意输入3个整数,求取三个整数中的最大值。c++
时间: 2024-05-03 21:22:01 浏览: 49
C++程序求三个整数中的最大值
以下是一个简单的ROS服务和客户端代码,用于求取三个整数中的最大值。
服务端代码:
```c
#include "ros/ros.h"
#include "demo_pkg/MaxInt.h"
bool max_int(demo_pkg::MaxInt::Request &req, demo_pkg::MaxInt::Response &res)
{
res.max = req.a;
if (req.b > res.max) {
res.max = req.b;
}
if (req.c > res.max) {
res.max = req.c;
}
ROS_INFO("Max of %d, %d and %d is %d", req.a, req.b, req.c, res.max);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "max_int_server");
ros::NodeHandle n;
ros::ServiceServer service = n.advertiseService("max_int", max_int);
ROS_INFO("Ready to find the max of 3 integers.");
ros::spin();
return 0;
}
```
客户端代码:
```c
#include "ros/ros.h"
#include "demo_pkg/MaxInt.h"
#include <cstdlib>
int main(int argc, char **argv)
{
ros::init(argc, argv, "max_int_client");
if (argc != 4) {
ROS_INFO("Usage: max_int_client a b c");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<demo_pkg::MaxInt>("max_int");
demo_pkg::MaxInt srv;
srv.request.a = atoi(argv[1]);
srv.request.b = atoi(argv[2]);
srv.request.c = atoi(argv[3]);
if (client.call(srv)) {
ROS_INFO("Max of %d, %d and %d is %d", srv.request.a, srv.request.b, srv.request.c, srv.response.max);
} else {
ROS_ERROR("Failed to call service max_int");
return 1;
}
return 0;
}
```
在运行之前,请确保已经创建了一个名为"demo_pkg"的ROS软件包,其中包含一个名为"MaxInt.srv"的服务文件,用于定义服务的请求和响应类型。"MaxInt.srv"文件内容如下:
```
int64 a
int64 b
int64 c
---
int64 max
```
在终端中先运行服务端:
```
$ rosrun demo_pkg max_int_server
```
然后在另一个终端中运行客户端,输入3个整数,例如:
```
$ rosrun demo_pkg max_int_client 5 2 7
```
将输出:
```
Max of 5, 2 and 7 is 7
```
阅读全文