MQTT是基於訂閱/發佈的物聯網協議。python
python測試須要一個發送進程和接收進程,即一個發送客戶端和一個接收客戶端,若是這兩個客戶端工做在同一個topic下,那麼就能進行消息互通了。服務器
服務器用「iot.eclipse.org」就行了,避免了本身搭建服務器,而後流程還能夠跑通。eclipse
發送客戶端代碼:oop
import paho.mqtt.client as mqtt import paho.mqtt.publish as publish idx = 0
#往paho/temperature 一直髮送內容 while True: print("send success") publish.single("paho/temperature", payload="this is message:%s"%idx, hostname="iot.eclipse.org", client_id="lora1", # qos = 0, # tls=tls, port=1883, protocol=mqtt.MQTTv311) idx += 1
接收客戶端代碼:測試
import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): #在這裏處理業務邏輯 print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("iot.eclipse.org", 1883, 60)
#訂閱頻道 client.subscribe("paho/temperature") # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
而後運行兩個客戶端,就能夠在接收端收到消息了。this
MQTT服務器不負責存儲數據,須要編寫額外的接收客戶端來接收數據、分析、入庫等。spa
MQTT服務器用的是iot.eclipse.org,若是碰巧兩我的在用同一個頻道,那可能收到別人的消息哦~code
若是要搭建本身的MQTT服務器,那麼回頭再說。server
玩一玩就行了,不要給服務器增長太多負擔喲~blog
參考資料: