【发布时间】:2017-09-13 07:14:48
【问题描述】:
我设法发表了几个主题并阅读了其中一个。我需要做的是聆听和阅读所有已发布的主题并获取消息。这是我使用的代码:
-
向 3 个主题发布消息:
#!/usr/bin/env python3 import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("localhost",1883,60) client.publish("topic/1", "400 | 350 | 320 | 410"); client.publish("topic/2", "200 | 350 | 420 | 110"); client.publish("topic/3", "200 | 350 | 420 | 110"); client.disconnect(); -
订阅和阅读 1 个主题的消息
#!/usr/bin/env python3 import paho.mqtt.client as mqttClient import time def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") global Connected #Use global variable Connected = True #Signal connection else: print("Connection failed") def on_message(client, userdata, message): print "Message received : " + message.payload Connected = False broker_address= "localhost" port = 1883 client = mqttClient.Client("Python") client.on_connect= on_connect client.on_message= on_message client.connect(broker_address, port=port) client.loop_start() while Connected != True: time.sleep(0.1) client.subscribe("topic/2") try: while True: time.sleep(1) except KeyboardInterrupt: print "exiting" client.disconnect() client.loop_stop()
【问题讨论】:
-
您的发布代码也有问题,您需要在每次发布之间调用client.loop函数以确保它们都刷新到网络堆栈,或者使用单/多发布功能( pypi.python.org/pypi/paho-mqtt/1.1#id17)