因此,我创建了此代码以使用Paho MQTT发送和接收消息。它吸收了用户的输入并发布到给定的主题,并且为了获得输入,我创建了一个while循环,如果输入为“ exit”,它将中断。
问题是我可以向该主题发送消息,但无法接收。 我只在输入“ exit”作为输入时收到它们。
我尝试阅读文档,但没有帮助,再加上我是python的新手,所以也许我错过了一些东西
import paho.mqtt.client as mqtt
import os
from urllib.parse import urlparse
# Define event callbacks
def on_connect(client, userdata, flags, rc):
print("rc: " + str(rc))
def on_message(client, obj, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_publish(client, obj, mid):
print("mid: " + str(mid))
def on_subscribe(client, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(client, obj, level, string):
print(string)
mqttc = mqtt.Client(client_id="NV")
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
topic = 'test'
# Connect
mqttc.username_pw_set(username, pass)
mqttc.connect(server,port)
mqttc.loop_start()
# Start subscribe, with QoS level 0
mqttc.subscribe(topic, 0)
# Publish a specififc message
mqttc.publish(topic,'NV Online')
# INPUT from User
msg = 'run'
while(msg!='exit'):
msg = input()
mqttc.publish(topic,msg)
编辑1: 平台: Eclipse Paho版本1.4 操作系统:Windows 7
答案 0 :(得分:0)
尝试将您的print
呼叫更改为包括flush=True
。
例如
def on_message(client, obj, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload), flush=True)