一张图看懂service通讯
Service通讯分为client端
和server端
。
client端
负责发送请求(Request)给server端
。server端
负责接收client端
发送的请求数据。server端
收到数据后,根据请求数据和当前的业务需求,产生数据,将数据(Response)返回给client端
。
Service通讯的特点:
- 同步数据访问
- 具有响应反馈机制
- 一个server多个client
- 注重业务逻辑处理
Service通讯的关键点:
service
的地址名称client端
访问server端
的数据格式server端
响应client端
的数据格式
c++ 代码如下
service:
#include <ros/ros.h>
#include <roscpp_tutorials/TwoInts.h>
bool callback(roscpp_tutorials::TwoInts::Request &request, roscpp_tutorials::TwoInts::Response &response) {
response.sum = request.a + request.b;
return true;
}
int main(int argc, char *argv[]) {
ros::init(argc, argv, "service_node");
ros::NodeHandle nodeHandle;
const ros::ServiceServer &server = nodeHandle.advertiseService("my_service", callback);
ros::spin();
}
client
#include <ros/ros.h>
#include <iostream>
#include <roscpp_tutorials/TwoInts.h>
using namespace std;
int main(int argc, char *argv[]) {
ros::init(argc,argv,"client_node");
ros::NodeHandle nodeHandle;
ros::ServiceClient client = nodeHandle.serviceClient<roscpp_tutorials::TwoInts>("my_service");
// 等待服务端上线
client.waitForExistence();
roscpp_tutorials::TwoInts twoInts;
twoInts.request.b = 10;
twoInts.request.a = 20;
client.call(twoInts);
cout << twoInts.response.sum << endl;
}
python
service:
#!/usr/bin/env python
#coding:utf-8
import rospy
from roscpp_tutorials.srv import TwoInts ,TwoIntsResponse
def callback(request):
response = TwoIntsResponse()
response.sum = request.a + request.b;
return response
if __name__ == '__main__':
rospy.init_node("py_service_node")
rospy.Service("py_service",TwoInts,callback)
rospy.spin()
client:
#!/usr/bin/env python
#coding:utf-8
import rospy
from roscpp_tutorials.srv import TwoInts,TwoIntsRequest,TwoIntsResponse
if __name__ == '__main__':
nodeName = "py_clientnode"
rospy.init_node(nodeName)
rospy.wait_for_service()
proxy = rospy.ServiceProxy("py_service", TwoInts)
request = TwoIntsRequest()
request.a = 10
request.b = 20
response = proxy.call(request)
print response.sum
rospy.spin()
版权声明:本文为qq_23363425原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。