Server部分: #!/usr/bin/env python import sys import os import rospy #from beginner.srv import * from beginner.srv import AddTwoInts def add_two_ints_client(x,y): rospy.wait_for_service('add_two_ints')# rospy.wait_for_service(‘service的tipoc’) try: add_two_ints=rospy.ServiceProxy('add_two_ints',AddTwoInts)#client请求(request)后server的返回值(response)add_two_ints 通过rospy.ServiceProxy的方式向service发送(request)请求 resp1=add_two_ints(x,y) #将参数发送给server return resp1.sum except rospy.ServiceException, e: print "Service call failed: %s"%e def usage(): return "%s [x,y]"%sys.argv[0] if __name__=="__main__": if len(sys.argv)==3: x=int(sys.argv[1]) y=int(sys.argv[2]) else: print usage() sys.exit(1) print"Resquesting %s+%s"%(x,y) print"%s+%s=%s"%(x,y,add_two_ints_client(x,y))
Client部分: import rospy from beginner.srv import * #from beginner.srv import * #from beginner.srv import AddTwoInts def handle_add_two_ints(req): print("Returning[%s+%s=%s]"%(req.a,req.b,(req.a+req.b))) sum=req.a+req.b return AddTwoIntsResponse(sum) def add_two_ints_server(): rospy.init_node('add_two_ints_server') s = rospy.Service('add_two_ints',AddTwoInts,handle_add_two_ints)#服务节点,服务类型,这里必须和AddTwoInts.srv的文件名一致,处理函数 处理函数调用和返回实例化的AddTwoIntsRes print"Ready to add Two Ints" rospy.spin() if __name__=="__main__": add_two_ints_server()