mqtt基于python的发布和订阅代码实例
本次博客就MQTT在python3下的代码写了一个简单的demo,供参考。
一、环境准备:
1. python3环境,pip3
2. 执行命令,pip3 install paho-mqtt
3. 创建pub.py文件(touch pub.py)
4. 打开文件
二、编写发布代码
import paho.mqtt.client as mqtt c=mqtt.Client(client_id="123456789", clean_session=True, userdata=None, transport="tcp") c.connect(host="172.17.0.2", port=1883, keepalive=5) c.loop_start() while True: data=["test ok"] c.publish(topic="test", payload=(str)(data), qos=1), retain=False) time.sleep(10)
解释一下c.loopstart()这个函数
官方API是这样的描述的:
These functions implement a threaded interface to the network loop. Calling loop_start() once, before or after connect*(), runs a thread in the background to call loop() automatically. This frees up the main thread for other work that may be blocking. This call also handles reconnecting to the broker.
因此,翻译过来就是:这个函数就是用来提供一个可以循环连接消息代理服务器的线程。当我们构造好了connect函数之后,使用这个loopstart()方法,就可以完成对于消息的连续发布。因此,我们只需要在后面编写循环,就可以完成对于数据的循环发布。
具体参考:
三、编写订阅代码
import paho.mqtt.subscribe as sub def on_message_print(client, userdata, message): print(str(message.topic)+" "+str(message.payload)) sub.callback(callback=on_message_print,topics"test", qos=1, userdata=None, hostname="172.0.0.1",port=1883, client_id="987654321", keepalive=10)
具体的消息代理服务器的安装,可以参考
JAVA版本的代码,可以参考: