要注意:服务端和客户端的名字要统一
什么是线程死锁
A需要等B把装满水的桶放下 才能把水桶提走
B需要等A把水桶提走才能把自己的装满
假设A和B都要站在位置C工作
A:站在工位C将小桶水倒进大桶里
B:从C位置将装满水的大桶拎走
那么假设时刻D
B发现大桶里没有装满水 因此在位置C等待水满
A发现B在位置C等待 于是扛着自己的小水桶等B离开
造成死锁
客户端
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from village_interface.srv import BorrowMoney
class BaiPiaoNode(Node):
def __init__(self, name):
super().__init__(name)
self.get_logger().info("大家好,我是李三,李四他哥,我可以白嫖李四的小说!")
self.sub_ = self.create_subscription(String,"sexy_gril",self.recv_callback,10)
self.borrow_client = self.create_client(BorrowMoney,"borrow_money")
def recv_callback(self, novel):
self.get_logger().info("李三:我已经收到了:%s" % novel.data)
def borrow_response_callback(self, response):
"""
借钱回调函数
"""
if response.success:
self.get_logger().info("借到%d钱了,去吃麻辣烫" % response.money)
else:
self.get_logger().info("真抠门,连几块钱都不借")
def main(args=None):
rclpy.init(args=args)
node = BaiPiaoNode("li3")
rclpy.spin(node=node)
rclpy.shutdown()
服务端
import rclpy
from rclpy.node import Node
from std_msgs.msg import String,UInt32
from village_interface.srv import BorrowMoney
class WriterNode(Node):
def __init__(self,name):
super().__init__(name)
self.get_logger().info('大家好,我是%s.' % name)
# String 话题消息类型
# "sexy_gril" 话题名
# 10 话题发布类型
# self.create_publisher(消息类型, 话题名, 发布频率)
# 创建发布者
self.pub_novel = self.create_publisher(String, "sexy_gril", 10)
# self.create_subscription(消息类型,话题名,回调函数,队列长度)
# 创建订阅者
self.sub_money = self.create_subscription(UInt32,"sexy_gril_money",self.rev_money_callback,10)
# 创建客户端
self.borrow_server = self.create_service(BorrowMoney,"borrow_money",self.borrowmoney_callback)
self.timer_period = 5
self.timer = self.create_timer(self.timer_period,self.timer_callback)
self.counter = 0
self.count = 80
# 创建服务端回调函数
def borrowmoney_callback(self, request, response):
"""
request: 来自客户端的请求数据
response:来自服务端的响应数据
"""
self.get_logger().info("收到来自:%s的请求,目前账户里有%d元"%(request.name,self.count))
if request.money <= self.count * 0.1:
response.success = True
response.money = request.money
self.count -= request.money
self.get_logger().info("借钱成功,借出%d元,目前账户结余%d"%(request.money,self.count))
else:
response.success = False
response.money = 0
self.get_logger().info("借钱失败!!")
return response
def timer_callback(self):
msg = String()
msg.data = '第%d回:潋滟湖 %d 次偶遇胡艳娘' %(self.counter,self.counter)
self.pub_novel.publish(msg=msg)
self.get_logger().info("发布消息: %s" % msg.data)
self.counter = self.counter + 1
def rev_money_callback(self,money):
self.count = self.count + money.data
self.get_logger().info("收到了%d的钱"%money.data)
def hello(args=None):
rclpy.init(args=args)
li3_node = WriterNode("li4")
rclpy.spin(li3_node)
rclpy.shutdown()