以下使用python的套件
首先安裝paho
pip install paho-mqtt
主程式碼如下
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("成功")
client.subscribe("test/topic")
else:
print(f"失败:{rc}")
def on_message(client, userdata, msg):
print(f"收到訊息:{msg.topic} {msg.payload.decode()}")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# 你的MQTT網址跟port號)
client.connect("mqtt_server_address", 1883, 60)
client.loop_start()
# 指定主题發布
client.publish("test/topic", "Hello, MQTT!")
try:
while True:
pass
except KeyboardInterrupt:
pass
client.disconnect()