Python使用mqtt通讯

各位兄弟请教一下现在我用Python编写mqtt本地通讯测试在pycharm上测试没有问题但是转移代码到软件上显示错误

img


兄弟请求指点一下
这是客户端订阅接收代码

img


这是客户端发送代码

img

MQTT是一种轻量级的发布/订阅消息传输协议,它可以在物联网(IoT)环境中使用,用于在设备之间传输数据。

Python可以使用MQTT协议来实现物联网应用。要使用MQTT,首先需要安装MQTT客户端库,例如paho-mqtt。

安装paho-mqtt:

pip install paho-mqtt

安装完成后,可以使用以下代码来连接MQTT服务器:

import paho.mqtt.client as mqtt

The callback for when the client receives a CONNACK response from the server.

def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))

Create an MQTT client and attach our routines to it.

client = mqtt.Client()
client.on_connect = on_connect

Connect to the test MQTT broker.

client.connect("test.mosquitto.org", 1883, 60)

Process network traffic and dispatch callbacks. This will also handle

reconnecting. Check the documentation at

https://github.com/eclipse/paho.mqtt.python

for information on how to use other loop*() functions

client.loop_forever()

上面的代码将客户端连接到MQTT服务器,并在连接成功时调用on_connect回调函数。

要发布消息,可以使用以下代码:

client.publish("topic/test", "Hello world!")

要订阅消息,可以使用以下代码:

The callback for when a PUBLISH message is received from the server.

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

Subscribing in on_connect() means that if we lose the connection and

reconnect then subscriptions will be renewed.

client.subscribe("topic/test")

Attach the message callback

client.on_message = on_message

上面的代码将客户端订阅到“topic/test”主题,并在收到消息时调用on_message回调函数。