【问题标题】:Why can't i receive messages in Paho MQTT?为什么我无法在 Paho MQTT 中接收消息?
【发布时间】:2019-08-16 06:52:23
【问题描述】:

所以我创建了这个代码来使用 Paho MQTT 发送和接收消息。它从用户那里获取输入并发布到给定的主题,为了获取输入,我创建了一个 while 循环,如果输入是“退出”,它将中断。

问题是我可以向主题发送消息但我无法接收它们。 我只有在输入“退出”时才会收到它们。

我尝试阅读文档,但没有任何帮助,而且我是 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

【问题讨论】:

  • 你是如何运行这段代码的?使用 python3 对我来说运行得很好。我只能假设您是从 shell 以外的其他东西运行它,并且输出正在缓冲,直到脚本退出。
  • 它在 Shell 上对我不起作用。除非我输入“退出”,否则我无法接收消息
  • 编辑问题以包含有关在何处(例如操作系统、版本)以及您如何运行此代码的更多信息。
  • 我现在已经包含了这些细节
  • 这没什么用,添加更多细节

标签: python mqtt paho


【解决方案1】:

尝试更改您的 print 调用以包含 flush=True

例如

def on_message(client, obj, msg):
  print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload), flush=True)

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2014-08-13
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多