本次博客就MQTT在python3下的代碼寫了一個簡單的demo,供參考。
一、環境準備:
1. python3環境,pip3
2. 執行命令,pip3 install paho-mqtt
3. 創建pub.py文件(touch pub.py)
4. 打開文件
二、編寫發佈代碼
import paho.mqtt.client as mqtt
c=mqtt.Client(client_id="123456789", clean_session=True, userdata=None, transport="tcp")
c.connect(host="172.17.0.2", port=1883, keepalive=5)
c.loop_start()
while True:
data=["test ok"]
c.publish(topic="test", payload=(str)(data), qos=1), retain=False)
time.sleep(10)
解釋一下c.loopstart()這個函數
官方API是這樣的描述的:
These functions implement a threaded interface to the network loop. Calling loop_start() once, before or after connect*(), runs a thread in the background to call loop() automatically. This frees up the main thread for other work that may be blocking. This call also handles reconnecting to the broker.
因此,翻譯過來就是:這個函數就是用來提供一個可以循環連接消息代理服務器的線程。當我們構造好了connect函數之後,使用這個loopstart()方法,就可以完成對於消息的連續發佈。因此,我們只需要在後面編寫循環,就可以完成對於數據的循環發佈。
具體參考:https://pypi.org/project/paho-mqtt/
三、編寫訂閱代碼
import paho.mqtt.subscribe as sub
def on_message_print(client, userdata, message):
print(str(message.topic)+" "+str(message.payload))
sub.callback(callback=on_message_print,topics"test", qos=1, userdata=None, hostname="172.0.0.1",port=1883, client_id="987654321", keepalive=10)
具體的消息代理服務器的安裝,可以參考
https://blog.csdn.net/sullivan_jia/article/details/80089187
JAVA版本的代碼,可以參考: