无法在Python中将消息发布到MQTT主题

时间:2018-07-19 18:01:10

标签: python python-3.x mqtt mosquitto paho

我在docker上运行Mosquito MQTT如下:

  broker:
    image: "toke/mosquitto"
    ports:
      - "1883:1883"
      - "9001:9001"

然后,我要订阅主题queue1,发布一条消息ON,并确认它已发布(即使用它)。 这是我当前的代码:

def on_connect(client, userdata, flags, rc):
    print('connected (%s)' % client._client_id)


def on_message(client, userdata, message):
    print('------------------------------')
    print('topic: %s' % message.topic)
    print('payload: %s' % message.payload)
    print('qos: %d' % message.qos)


broker = "localhost"
port = 1883
mqttc = mqtt.Client("client")
mqttc.on_connect = on_connect
mqttc.on_message = on_message
print("connecting to broker ", broker)
mqttc.connect(broker, port, 60)

mqttc.loop_start()
print("subscribing ")
mqttc.subscribe("queue1")
time.sleep(2)
print("publishing ")
res = mqttc.publish("queue1","ON")
time.sleep(10)
mqttc.disconnect()
mqttc.loop_stop()

但这给了我以下反馈。看起来该消息未发布:

connecting to broker  127.0.0.1
subscribing 
connected (b'client')
publishing 
------------------------------
topic: queue1
payload: b'ON'
qos: 0

0 个答案:

没有答案