Title:
Python使用 paho-mqtt 库来实现 MQTT 客户端,以接收和发布消息。
[Print this page]
Author:
sky999
Time:
2023-11-27 11:26
Title:
Python使用 paho-mqtt 库来实现 MQTT 客户端,以接收和发布消息。
import paho.mqtt.client as mqtt # MQTT 服务器信息 broker_address = "mqtt.eclipse.org" port = 1883 topic = "test_topic" # 回调函数,当连接成功时被调用 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # 订阅主题 client.subscribe(topic) # 回调函数,当接收到消息时被调用 def on_message(client, userdata, msg): print(f"Received message on topic {msg.topic}: {msg.payload.decode()}") # 创建 MQTT 客户端 client = mqtt.Client() # 设置连接成功和消息接收的回调函数 client.on_connect = on_connect client.on_message = on_message # 连接到 MQTT 服务器 client.connect(broker_address, port, 60) # 保持运行,等待消息 client.loop_forever() [
本帖最后由 sky999 于 2023-11-27 11:32 编辑
]
Image attachment:
微信图片_20231127113216.png
(2023-11-27 11:32, 21.65 K) / Number of times this attachment has been downloaded 115
http://iot.caffz123.uk:12345/mud/AbyssalSwamp/index/attachment.php?aid=2572
Welcome AbyssalSwamp (http://iot.caffz123.uk:12345/mud/AbyssalSwamp/index/)
caffz.com