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()

你可能感兴趣的:(Python,Testtools,MQTT,MQTTSubscribe,订阅消息,python,paho)