我使用Mosquitto(现在的Paho)python MQTT客户端连接到HiveMQ代理。代码非常基础,取自他们的文档 - https://pypi.python.org/pypi/paho-mqtt
#SUBSCRIBER
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
client.subscribe("GB/node0/", 2)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print "Topic: ", msg.topic+'\nMessage: '+str(msg.payload)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.15.4", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
client.loop_forever()
正如您在client.subscribe()中注意到的那样,QoS是2.这是对官方文档代码的唯一修改。
发布客户的代码是 -
#PUBLISHER
import paho.mqtt.client as mqtt
mqttc = mqtt.Client("python_pub")
mqttc.connect("192.168.15.4", 1883, 60)
mqttc.publish("GB/node0/", "Hello, World baby!",2)
此处,QoS也是2.
QoS的这种修改导致订户仅接收20条消息。在进一步探测之后,我意识到问题可能是由max_inflight_messages_set()
引起的,{{1}}是一个选项函数,它设置QoS> 0的最大消息数,这些消息可以同时通过其网络流。默认值为20.
但是,将其更改为任何其他值都不起作用。此外,为什么客户认为这些消息在收到后仍然存在?我该如何解决这个问题?我如何确保客户理解这些消息不是" inflight"并已交付?
答案 0 :(得分:4)
尝试在发布商mqttc.loop(2,10)
之后调用mqttc.publish()
,以便发布商可以处理来自代理的已收到发布的QOS2确认。
2秒超时和10个数据包可能超过需要但它应该工作
答案 1 :(得分:4)
@hardillb是对的,你需要某种形式的loop*()
电话。更确切地说,这样做:
import paho.mqtt.client as mqtt
def on_publish(client, userdata, mid):
client.disconnect()
mqttc = mqtt.Client() # There's normally no need to set a client id.
mqttc.on_publish = on_publish
mqttc.connect("192.168.15.4", 1883, 60)
mqttc.publish("GB/node0/", "Hello, World baby!",2)
mqttc.loop_forever()
或者:
import paho.mqtt.publish as paho
paho.single("GB/node0/", "Hello, World baby!", qos=2, hostname="192.168.15.4")