首页 > 解决方案 > Python 3.7 /Mosquitto 的问题

问题描述

我想通过本地网络使用 Ubuntu Server 18.04.5 和带有 Rasperian 10 的 RasperryPi 与 MQTT 交换消息。代理正在运行,当我通过控制台从 Raspberry 订阅时,它可以工作。但是当我尝试使用 Python 连接到代理时,我收到以下错误:

1622369636: New connection from 192.168.0.11 on port 1883.
1622369636: New client connected from 192.168.0.11 as SMS_Daemon (c1, k60).
1622369636: Sending CONNACK to SMS_Daemon (0, 0)
1622369706: Socket error on client SMS_Daemon, disconnecting.

在 Mosquitto 的日志文件中

我有一个教程的代码,当它不起作用时,我使用了另一个教程的代码,但收到了同样的错误。我发现 Ubuntu 18.04 使用 Mosquitto 1.4.15 和 Raspberry 1.5.7。两个版本都来自标准存储库。

这里是 Python 代码。

# -*- coding: utf8' -*-
import paho.mqtt.client as mqtt

mqttTopic = 'RaspberryPi1/SMS_Daemon'

def connect_msg():
    print("Connect to broker")

def publish_msg():
    print("Message published")

mqttClient = mqtt.Client(client_id='SMS_Daemon') 
mqttClient.on_connect = connect_msg 
mqttClient.on_publish = publish_msg 
mqttClient.connect("192.168.0.1",1883)  

任何人都知道我可以在哪里搜索解决方案或我的问题在哪里?

提前致谢

标签: pythonmosquitto

解决方案


您尚未启动 MQTT 客户端循环。

你应该添加

mqttClient.loop_forever()

在最后一行之后

此外,提供的代码实际上除了打印之外不会做任何事情Connect to broker


推荐阅读