为什么 on_publish 回调在 on_connect 之前被调用?
Why is the on_publish callback being called before on_connect?
我编写的代码的输出是
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
将对 subscribe
和 publish
的调用移至 on_connect
回调内部,然后您可以在尝试订阅主题和发布消息之前确保连接成功.
如果代理出现问题,其他任何操作都会失败。
我编写的代码的输出是
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
将对 subscribe
和 publish
的调用移至 on_connect
回调内部,然后您可以在尝试订阅主题和发布消息之前确保连接成功.
如果代理出现问题,其他任何操作都会失败。