Python3 订阅MQTT消息(模拟终端)

上一篇博文写了发布,这个博文写订阅。用的是同一个主题。

如果是自己写的话,需要知道:1、MQTT服务器的地址(端口默认1883)2、需要订阅的主题

代码:

# -*- coding: utf-8 -*-
# @Time : 2020/3/16 0016 9:32
# @Author : Liqiju
# @File : MQTTSubscribe.py
# @Software : PyCharm
import paho.mqtt.client as mqtt

#MQTT服务器
host = "XXX.XX.XX.XXX"
#端口
port = 1883
#主题
topic = "config/1/devices/CC10501000000015/rx"

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

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

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, port, 60)
client.loop_forever() #保持连接,有消息就接受打印出来

当有其他终端发布者主题消息的时候,这里就可以看到了。

截图:返回0,表示连接成功

消息已成功收到。

下面是多线程实现:

import paho.mqtt.client as mqtt
import threading
 
# MQTT服务器
host = "XXX.XX.XX.XXX"
# 端口
port = 1883
# 主题
topic = "config/1/devices/CC10501000000015/rx"
 
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(topic)
 
def on_message(client, userdata, msg):
    print(msg.topic + " " + ":" + str(msg.payload))
 
def mqtt_subscriber():
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(host, port, 60)
    client.loop_forever()
 
# 创建多个线程并发执行订阅操作
num_threads = 5  # 设置线程数量
threads = []
for _ in range(num_threads):
    t = threading.Thread(target=mqtt_subscriber)
    t.start()
    threads.append(t)
 
# 等待所有线程完成
for t in threads:
    t.join()

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

软件测试李同学

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

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

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

打赏作者

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

抵扣说明:

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

余额充值