Python实现Client端

Client创建流程

1. 创建节点

1
rospy.init_node(nodeName)

2. 调用Service

1
2
3
4
5
6
# 等待服务器连接
rospy.wait_for_service(serviceName)
# 创建服务调用代理
call = rospy.ServiceProxy(serviceName, TwoInts)
# 调用服务
result = call(4, 9)

完整代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
# coding:utf-8

import rospy
from rospy_tutorials.srv import AddTwoInts, AddTwoIntsRequest, AddTwoIntsResponse

if __name__ == '__main__':
    # 创建节点
    nodeName = "my_client_node"
    rospy.init_node(nodeName)

    # 创建Service Client
    serviceName = "my_service"
    client = rospy.ServiceProxy(serviceName, AddTwoInts)

    # 等待服务开启
    rospy.wait_for_service(serviceName)

    # 创建请求数据
    request = AddTwoIntsRequest()
    request.a = 4
    request.b = 5
    # 调用服务并且获得响应结果
    response = client.call(request)

    if isinstance(response, AddTwoIntsResponse):
        rospy.loginfo("响应结果: %d" % response.sum)

    # 阻塞线程
    rospy.spin() 

调试Client端

通过已有的server来调试client

1
rosrun demo_service client.py