MQTT协议使用消息队列

MQTT协议使用消息队列示例
示例代码
 
#!/usr/bin/env python
# encoding: utf-8
#导入mosquitto的python库
 
#import mosquitto
import paho.mqtt.client as paho
 
# 定义自己的callback 函数
 
def on_connect(mosq, obj, rc):
   mosq.subscribe("$SYS/#", 0)
   print("rc: "+str(rc))
 
def on_message(mosq, obj, msg):
   print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
 
def on_publish(mosq, obj, mid):
   print("mid: "+str(mid))
 
def on_subscribe(mosq, obj, mid, granted_qos):
   print("Subscribed: "+str(mid)+" "+str(granted_qos))
 
def on_log(mosq, obj, level, string):
   print(string)
 
# 创建客户端
# If you want to use a specific client id, use
# mqttc = mosquitto.Mosquitto("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
#mqttc = mosquitto.Mosquitto()
mqttc = paho.Client()
 
# 注册callback函数
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
 
# 连接服务器
#mqttc.connect("test.mosquitto.org", 1883, 60)
mqttc.connect("172.17.0.2", 1883, 60)
 
# 订阅消息
mqttc.subscribe("string", 0)
#mqttc.subscribe(("tuple", 1))
#mqttc.subscribe([("list0", 0), ("list1", 1)])
 
# 无限循环处理
mqttc.loop_forever()

标签

发表评论