python3 mqtt 發布以及訂閱


安裝庫
pip3 install paho-mqtt
 
發布話題
import paho.mqtt.client as mqtt
import time
import sys
 
 
HOST = "103.77.337.89"
PORT = 1883
 
 
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
    print("消息發送成功")
 
 
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.connect(host=HOST, port = PORT, keepalive=60)  # 訂閱頻道
time.sleep(1)
i = 0
 
 
while True:
    try:
        # 發布MQTT信息
        sensor_data = "test" + str(i)
        client.publish(topic="public", payload=sensor_data.encode("utf-8"), qos=0)
        time.sleep(3)
        i += 1
    except KeyboardInterrupt:
        print("EXIT")
        client.disconnect()
        sys.exit(0)
 

 

 
 
訂閱話題
import time
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
 
 
HOST = "103.77.337.89"
PORT = 1883
 
 
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("連接成功")
        print("Connected with result code " + str(rc))
 
 
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
client.connect(host=HOST, port = PORT, keepalive=60)  # 訂閱頻道
time.sleep(1)
client.subscribe("public")
#client.subscribe([("public", 0), ("test", 2)])
client.loop_forever()

 

 
 
 
訂閱話題
import time
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
 
 
HOST = "103.77.337.89"
PORT = 1883
 
 
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("連接成功")
        print("Connected with result code " + str(rc))
 
 
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
client.connect(host=HOST, port = PORT, keepalive=60)  # 訂閱頻道
time.sleep(1)
client.subscribe("SJHTopic2")
#client.subscribe([("public", 0), ("test", 2)])
client.loop_forever()

 

 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM