Ros中写一个服务端代码和客户端代码,写一个srv文件,客户端发送两个数字,服务端返回二者的最大公因数
时间: 2023-03-31 19:02:47 浏览: 101
服务端代码:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import Int64
from beginner_tutorials.srv import Gcd, GcdResponse
def gcd(req):
a = req.a
b = req.b
while b:
a, b = b, a % b
return GcdResponse(a)
def gcd_server():
rospy.init_node('gcd_server')
s = rospy.Service('gcd', Gcd, gcd)
print("Ready to calculate gcd.")
rospy.spin()
if __name__ == "__main__":
gcd_server()
```
客户端代码:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from beginner_tutorials.srv import Gcd, GcdRequest
def gcd_client(x, y):
rospy.wait_for_service('gcd')
try:
gcd = rospy.ServiceProxy('gcd', Gcd)
resp = gcd(x, y)
return resp.gcd
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
if __name__ == "__main__":
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Requesting %s and %s"%(x, y))
print("GCD is %s"%(gcd_client(x, y)))
```
srv文件:
```python
int64 a
int64 b
---
int64 gcd
```
注意:以上代码仅供参考,具体实现可能需要根据实际情况进行修改。