简体   繁体   English

paho.mqtt.client 订阅后收不到消息

[英]paho.mqtt.client doesn't receive messages after subscription

I've wrote a little listener for my mosquitto server, code is provided.我为我的 mosquitto 服务器编写了一个小监听器,提供了代码。 If i listen with the mosquitto_sub command, i correctly receive my published messages, but the python doesn't receive anything.如果我使用 mosquitto_sub 命令收听,我会正确收到我发布的消息,但 python 没有收到任何内容。 I just have the "Connected" message.我只有“已连接”消息。 Please help.请帮忙。

import logging
from paho.mqtt.client import Client

logging.basicConfig(level="INFO")

def on_connect(client, userdata, flags, rc):
  logging.info("Connected")
  client.subscribe("test")

def on_message(client, userdata, msg):
  logging.info("Received " + msg)

client = Client("listener")
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost")
client.loop_forever()

The problem is with your logging line in the on_message callback.问题在于on_message回调中的日志记录行。

It doesn't know how to log the msg object它不知道如何记录msg object

Change it to the following:将其更改为以下内容:

def on_message(client, userdata, msg):
  logging.info("Received " + str(msg.payload))

This converts the msg's payload to a string.这会将 msg 的有效负载转换为字符串。

EDIT:编辑:

It is also worth pointing out that all the callbacks get run in a try/expect block that throws away any errors generated (hence the silent failure).还值得指出的是,所有回调都在try/expect块中运行,该块会丢弃生成的任何错误(因此是静默失败)。 Add your own try/expect blocks in the callback to trap and handle any errors that might occur.在回调中添加您自己的try/expect块以捕获和处理可能发生的任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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