首页 > 解决方案 > 为主题创建多个客户端

问题描述

从 Sqlite3 数据库中,我正在收集多个要订阅的 mqtt 主题。我从数据库中挑选主题并将它们放入列表中。现在我想为每个主题(列表中的每个项目)创建一个客户端并订阅该主题。这样我就有多个订阅不同主题的客户。

这就是我从数据库中获取主题的方式:

connection = sqlite3.connect(MainDatabaseDirectory)
cursor = connection.cursor() 
cursor.execute("""SELECT * FROM 'List'""")
for dataset in cursor:
    topic = ''.join(dataset[0])
    topicList.append(topic) 

这就是我尝试创建多个客户端并订阅主题的方式:

   for i in range(len(topicList)):
       topic = ''.join(topicList[i])
       client = mqtt.Client(topic)
       client.connect(mqttBrokerIpAddress, Port)
       client.subscribe(topic)

谁能告诉我,我的问题在哪里或者我需要做的更好吗?甚至可以创建多个客户端来订阅不同的主题吗?

标签: pythonmqttsubscribe

解决方案


好的,首先你真的不想在没有非常好的理由的情况下在同一个进程中创建多个客户端(我能想到的唯一一个是代表具有不同 ACL 的多个用户的后端服务器)。

一个客户可以订阅许多主题(正如我们在您第一次发布时的答案中所讨论的那样)。

您发布的代码正在创建多个客户端,但随后立即丢弃对它们的任何引用并用它创建的下一个客户端覆盖它。

创建 1 个客户端,订阅多个主题。

def on_connect(client, userdata, flags, rc)
  global topicList
  for i in range(len(topicList)):
       topic = ''.join(topicList[i])
       client.subscribe(topic)

def on_message(client, userdata, message)
  # do something with the message
  # the topic the message arrived on will be in
  # message.topic

connection = sqlite3.connect(MainDatabaseDirectory)
cursor = connection.cursor() 
cursor.execute("""SELECT * FROM 'List'""")
for dataset in cursor:
    topic = ''.join(dataset[0])
    topicList.append(topic) 

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqttBrokerIpAddress, Port)
client.loop_forever()

推荐阅读