为什么在on_connect之前调用on_publish回调?

时间:2019-02-22 06:40:46

标签: python mqtt paho

我所写代码的输出是

on_publish
('Connected', '0')
('message received ', 'test1234')
('message topic=', u'paho/test')

代码如下:

import paho.mqtt.client as mqtt  
import time import json

def on_connect(client,data,flag,rc):
    print("Connected",str(rc))

def on_publish(client,data,msg):
    print("on_publish")

def on_message(client, userdata, message):
    print("message received " ,str(message.payload.decode("utf-8")))
    print("message topic=",message.topic)

broker_address="iot.eclipse.org"

client = mqtt.Client()

client.on_connect=on_connect
client.on_publish=on_publish 
client.on_message=on_message 

client.connect(broker_address,1883) #connect to broker 
client.loop_start()  
data="test1234" 
client.subscribe("paho/test") 
client.publish("paho/test",data) 
time.sleep(4) # wait 
client.loop_stop() #stop the loop

1 个答案:

答案 0 :(得分:0)

将对subscribepublish的调用移到on_connect回调中,然后可以确保在尝试订阅主题和发布消息之前连接已成功。< / p>

如果代理出现问题,其他任何事情都将严重失败。