丢失订阅消息按Qos = 2发布

时间:2015-05-19 08:01:02

标签: python mqtt

我在主题" OK /主题"上订阅消息对于Qos = 2但有时我没有通过Qos = 2发布消息,遵循我的订阅代码:

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("OK/Topic",2)

def on_message(client, userdata, msg):
    print(" Topic : "+str(msg.topic)+"  and Message is : "+str(msg.payload))

def on_subscribe(client, userdata,mid, granted_qos):
    print "userdata : " +str(userdata)


strs="my-message-to-publish"
mqttc = mqtt.Client("Python-MQTT-Pub-Sub")
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_subscribe = on_subscribe
mqttc.connect("IP", PORT, 60)
mqttc.start_loop()
while True:
    mqttc.publish("New/Topic",str(strs))
    print "publish message " + str(strs)
    time.sleep(1)

我的发布商代码在主题" OK /主题"如下:

def on_publish(client, userdata, mid):
    client.disconnect()

mqttc = mqtt.Client()
mqttc.on_publish = on_publish
mqttc.publish("OK/Topic","my_message",2)

如果我发布10条消息,我会收到订阅者7-8消息,但不会消息10 任何人都知道为什么我错过了一些消息。

谢谢.. !!!

1 个答案:

答案 0 :(得分:1)

在完整的QOS2进程可以干净地完成之前,在on_publish方法中调用disconnect很可能会关闭连接。

而不是使用publish和on_publish来断开尝试使用单一方法在一个同步方法中进行完全连接,发布,清理:

import paho.mqtt.publish as publish

publish.single(topic, payload=None, qos=0, retain=False, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None,protocol=mqtt.MQTTv311)