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

问题描述 投票:-1回答:1

我写的代码的输出是

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
python mqtt paho
1个回答
0
投票

将调用subscribepublish移到on_connect回调中,然后在尝试订阅主题并发布消息之前,您可以确定连接已成功。

如果经纪人出现问题,其他任何事情都会失败。

© www.soinside.com 2019 - 2024. All rights reserved.