简体   繁体   中英

Mqtt subscribe message while continuous publishing to topic

I am trying to Publish message to topic "New/Topic" and subscribe message from another topic "OK/Topic" but it doesn't work following is my code :

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("OK/Topic")

def on_message(client, userdata, msg):
    print(" Topic : "+str(msg.topic)+"  and Message is : "+str(msg.payload))

def on_subscribe(client, userdata,mid, granted_qos):
    print "userdata : " +str(userdata)


strs="my-message-to-publish"
mqttc = mqtt.Client("Python-MQTT-Pub-Sub")
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_subscribe = on_subscribe
mqttc.connect("IP", PORT, 60)

while True:
    mqttc.publish("New/Topic",str(strs))
    print "publish message " + str(strs)
    time.sleep(1)

mqttc.loop_forever()

Anyone knows how to subscribe message while continuous publishing to topic.

Thanks in advance.

Your while loop will never terminate so the code will never reach the mqttc.loop_start() function. This is what's causing the problem you are seeing.

If you move the mqttc.loop_start call to before the while loop it should do better as it will start the background thread to handle the incoming messages (and to actually send the published messages)

The following code will work perfectly:

while True:
        client.connect(broker_address, port)
        message = 'msg'      
        client.publish(topic, message)
        time.sleep(1)
client.loop_forever()`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM