python - 为主题创建多个客户端
问题描述
从 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)
谁能告诉我,我的问题在哪里或者我需要做的更好吗?甚至可以创建多个客户端来订阅不同的主题吗?
解决方案
好的,首先你真的不想在没有非常好的理由的情况下在同一个进程中创建多个客户端(我能想到的唯一一个是代表具有不同 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()
推荐阅读
- git - git fetch 不工作,但 pull 工作
- google-cloud-run - 在 Google Cloud Run 上进行服务到服务调用时出现奇怪的延迟
- ruby-on-rails - 无法在 Rails + webpacker 中加载 slick-carousel
- angular - Angular 应用程序提供 mime 错误,并且在部署到 kubernetes 入口后无法在浏览器上加载
- c# - 基于体素的游戏的纹理映射或纹理平铺?(统一)
- java - 如何使用 spring-boot 访问 websocket 连接中的请求?
- dart - 如何在飞镖脚本中从键盘重定向标准输入?
- r - 根据一个因素出现的次数绘制两个因素变量
- python - 更改 Seaborn 应用调色板的轴
- c# - 如何在 C#、.net 中找到 JObject 的必填字段?