我正在使用Mosquitto和Paho的Python实现来尝试传达几个程序.当我使用最后一个功能时,我遇到了一些麻烦.我的代码是这样的:
会员键:
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print 'Received: ' + msg.payload
client = mqtt.Client()
client.on_message = on_message
client.connect('localhost', 1883)
client.subscribe('hello/#')
client.loop_forever()
出版商:
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.will_set('hello/will', 'Last will', 0, False)
client.connect('localhost', 1883)
client.publish('hello/world', 'Regular msg', 0, False)
client.disconnect()
输出:
Received: Last will
我应该只收到常规消息,因为我使用client.disconnect()来关闭连接.如果我评论will_set行,我会收到常规消息.我也尝试在同一主题上发布它们并且它不起作用.
解决方法:
您可以尝试使用单一方法只发布一条消息,如下所示:
import paho.mqtt.publish as publish
publish.single('hello/world', 'Regular msg', 0, False, 'localhost' , 1883, 'publisher', 10, {'topic': 'hello/will', 'payload': 'Will msg', 'qos': 0, 'retain': False})
https://pypi.python.org/pypi/paho-mqtt#single
我猜想问题是你在发布实际完成之前断开连接,这可能就是你看到遗嘱信息的原因.
编辑 –
当我使用mosquitto_sub -v -t’hello /#’运行你的代码时,我看到了正常的消息和正在传递的意愿.
EDIT2 –
这对我来说很好:
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.will_set('hello/will', 'Last will', 0, False)
client.connect('localhost', 1883)
client.publish('hello/world', 'Regular msg', 0, False)
client.loop();
client.disconnect()
client.loop();