Article directory
foreword
Learning record, error summary
1. Service communication (python)
Done with python.
2. Use steps
1. Server
The code is as follows (example):
#! /usr/bin/env python
import rospy
from plumbing_server_client.srv import AddInts,AddIntsRequest,AddIntsResponse
"""
服务段:解析客户端的请求,产生响应
1、导包
2、初始化节点
3、创建服务端的对象
4、处理逻辑(回调函数) 发生时间不确定用回调函数
5、回调函数必带spin()
"""
def doNum(request):
# 解析提交的两个整数
num1 = request.num1
num2 = request.num2
# 求和
sum = num1+num2
# 将结果封装进响应
response = AddIntsResponse() # 创建一个response对象类型是AddIntsResponse
response.sum = sum
rospy.loginfo("服务器接收到的请求数据是:num1=%d,num2=%d,响应结果是sum=%d",num1,num2,sum)
return response
if __name__=="__main__":
#2、初始化节点
rospy.init_node("heiShui")
# 3、创建服务端的对象
server=rospy.Service("addInts",AddInts,doNum)
rospy.loginfo("服务器启动成功")
# 4、处理逻辑(回调函数) 发生时间不确定用回调函数
# 5、回调函数必带spin()
rospy.spin()
2. Client
The code is as follows (example):
#! /usr/bin/env python
from http import client
from urllib import response
import rospy
from plumbing_server_client.srv import AddInts,AddIntsRequest,AddIntsResponse
"""
客户端:发出请求,处理服务端响应
1、导包
2、初始化节点
3、创建客户端的对象
4、发出请求
5、处理响应
"""
if __name__=="__main__":
rospy.init_node("erHei")
client =rospy.ServiceProxy("addInts",AddInts)
response=client.call(1,2) #call函数会返回一个值用response接收它
rospy.loginfo("响应的数据是%d",response.sum)
3. Running results
Summarize
Error 1:
"/home/wht/at_demo/demo03_ws/src/plumbing_server_client/scripts/demo02_client_p.py", 第20行, in <module>.
rospy.loginfo("响应的数据是%d", response.sum)
AttributeError: 模块'urllib.response'没有属性'sum'。
Error analysis: because the function usage of client.call is not understood, it will return a value, which should be received by response, and its fields should be printed by rospy.loginfo: response=client.call(1,2)
learn 1: add sys file
It can be realized, dynamic input;
learning 2: the client hang function is not consistent with the c++ version;