--
1 |
MQTT 客户端整个生命周期的行为可以概括为:建立连接、订阅主题、接收消息并处理、向指定主题发布消息、取消订阅、断开连接。 |
節錄: MQTT 客户端库
--
公開 MQTT Borker
- The Free Global Public MQTT Broker | Try Now | EMQ (emqx.com) - broker.emqx.io:1883
- The Public MQTT Broker by HiveMQ - Check out our MQTT Demo - broker.hivemq.com:1883
HiveMQ Dashboard (mqtt-dashboard.com) HiveMQ 監控 - test.mosquitto.org - test.mosquitto.org:1883
- Sandboxes | IoT development made simple - mqtt.eclipse.org:1883
建議選擇 broker.emqx.io 或 broker.hivemq.com,這兩台主機同時支援 WebSocket 和 SSL 才可以測試網頁 WebSocket 和 MQTT 的通訊
--
程式參考
以下 Python 範例程式已經根據可用 MQTT Broker 修改
程式先訂閱 house/bulb1 主題,然後發行 house/bulb1 此主題及內容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import time import paho.mqtt.client as paho broker = "broker.emqx.io" # define callback def on_message(client, userdata, message): time.sleep(1) print("received message =", str(message.payload.decode("utf-8"))) client = paho.Client("client-001") # create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish("house/bulb1","on") ######Bind function to callback client.on_message = on_message ##### print("connecting to broker ", broker) client.connect(broker) # connect client.loop_start() # start loop to process received messages print("subscribing ") client.subscribe("house/bulb1") # subscribe print("publishing ") client.publish("house/bulb1", "on") # publish time.sleep(3) client.disconnect() # disconnect client.loop_stop() # stop loop |
運作結果
1 2 3 4 |
connecting to broker broker.emqx.io subscribing publishing received message = on |
--
Topic 萬用字元
#
1 2 3 4 5 |
finance/stock/ibm/# finance/stock/ibm finance/stock/ibm/closingprice finance/stock/ibm/currentprice |
+
1 2 3 4 5 6 |
finance/stock/+ /finance/stock/ibm /finance/stock/xyz 不匹配 /finance/stock/ibm/closingprice |
--
Workerman Socket VS MQTT
- MQTT 要接收的資料必須自己訂閱,少了多了都有問題,Socket 要自己處理資料流
- 傳送時斷線 Socket 就是失敗,MQTT 根據 QoS 政策可以保證資料的送達。當 QoS 為 0 時,短暫的斷線 (拔網路線10秒) 也能成功送達
- 主機端須處理的程式 Socket 可以寫在 Workerman 內,MQTT 因為 Server 只是代理,所以程式必須分開,以健康度來說 MQTT 較佳;Socket 程式一致性及即時性較佳
--
14,370 total views, 34 views today