ROS下简单的客户端服务器程序

1.创建工作空间
mkdir -p catkin_ws/src
创建一个包
cd catkin_ws/src
catkin_creat pkg beginner_tutorials
mkdir srv
cd srv
touch AddTwoInts.srv
sudo gedit AddTwoInts.srv
内容如下:
int64 a
int64 b

int64 sum
cd src
touch add_two_ints_client.cpp
gedit add_two_ints_client.cpp
代码如下:
#include “ros/ros.h”
#include “beginner_tutorials/AddTwoInts.h”
#include
int main(int argc, char **argv)
{
ros::init(argc, argv, “add_two_ints_client”);
if (argc!=3)
{
ROS_INFO(“usage: add_two_ints_client X 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”, (long int)srv.response.sum);
}
else
{
ROS_ERROR(“Failed to call service add_two_ints”);
return 1;
}
return 0;
}
touch add_two_ints_server.cpp
gedit add_two_ints_server.cpp
代码如下
#include “ros/ros.h”
#include “beginner_tutorials/AddTwoInts.h”
bool add(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 two ints.”);
ros::spin();
return 0;
}
接下来修改CmakeLists.txt
第一处:
find_package(catkin REQUIRED roscpp rospy std_msgs message_generation)
第二处
add_service_files(
FILES
AddTwoInts.srv
)
第三处
generate_messages(
DEPENDENCIES
std_msgs
)
第四处
include_directories(
${catkin_INCLUDE_DIRS}
)
第六处
add_executable(add_two_ints_server src/add_two_ints_server.cpp)
target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
add_dependencies(add_two_ints_server beginner_tutorials_gencpp)

add_executable(add_two_ints_client src/add_two_ints_client.cpp)
target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
add_dependencies(add_two_ints_client beginner_tutorials_gencpp)
然后在工作空间下
catkin_make
source devel/setup.bash
首先运行服务器节点
$ rosrun beginner_tutorials add_two_ints_server
再运行客户端节点
$ rosrun beginner_tutorials add_two_ints_client 1 3
在客户端节点会得到结果四,在服务器上会看到request: x=1, y=3
sending back response: [4]

你可能感兴趣的:(ROS下简单的客户端服务器程序)