如何在线程中运行MQTT订阅服务器

时间:2019-02-19 15:59:30

标签: python multithreading callback mqtt

我正在用python中的paho.mqtt开发一个MQTT订阅服务器。给定主题列表,我需要在单独的线程或过程中为每个主题启动一个订阅者。当我在主线程中运行订阅服务器时,我的代码运行良好,但如果在线程中运行订阅服务器,则永远不会调用回调。

import paho.mqtt.client as mqtt
import time
import threading

class MQTTSubscriber():

    def __init__(self, mqtt_server, mqtt_topic):
        self.__mqtt_server = mqtt_server
        self.__mqtt_topic = mqtt_topic

    def __on_message(self, client, userdata, message):

        payload = message.payload.decode("utf-8")
        print(payload)

    def start(self):

        self.__client = mqtt.Client("MQTTClient")
        self.__client.on_message = self.__on_message

        self.__client.connect(self.__mqtt_server)

        print("Subscribing to topic " + str(self.__mqtt_topic))
        self.__client.subscribe(self.__mqtt_topic)

        self.__client.loop_forever()

这是我的主程序:

topics = ["topic1", "topic2"]

for topic in topics:
    mqttSubscriber = MQTTSubscriber("10.0.1.174", topic)
    # mqttSubscriber.start()
    thread = threading.Thread(target = mqttSubscriber.start)
    thread.setDaemon(True)
    thread.start()

while True:
    pass

知道发生了什么事吗?

0 个答案:

没有答案