mqtt基于python的发布和订阅代码实例

本文介绍如何在Python3环境下使用paho-mqtt库实现MQTT协议的消息发布与订阅。通过创建发布者与订阅者的示例代码,演示了如何连接到MQTT服务器,并进行数据的发送与接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本次博客就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()方法,就可以完成对于消息的连续发布。因此,我们只需要在后面编写循环,就可以完成对于数据的循环发布。

具体参考:https://pypi.org/project/paho-mqtt/

三、编写订阅代码


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)







具体的消息代理服务器的安装,可以参考

https://blog.youkuaiyun.com/sullivan_jia/article/details/80089187

JAVA版本的代码,可以参考:

https://blog.youkuaiyun.com/sullivan_jia/article/details/81942659

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嫌疑人X的解忧杂货店

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值