1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import paho.mqtt.client as mqtt
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# MQTT 客户端回调函数
def on_connect(client, userdata, flags, rc):
logging.info("已连接到MQTT服务器")
# 订阅多个主题
topics = ["/androidPanel/", "/meeting/sign/result", "/meeting/message/sync", "/uams/android/broadcast", "/meeting/message/igzk5herl6mntnui3grjt04v3vq6m7z5/"]
for t in topics:
client.subscribe(t)
def on_message(client, userdata, msg):
logging.info(f"接收到消息: 主题={msg.topic}, 消息体={msg.payload.decode()}")
if __name__ == "__main__":
broker_address = "192.168.1.193"
port = 1883
username = "mqtt@cmdb"
password = "mqtt@webpassw0RD"
# 创建 MQTT 客户端实例
mqtt_client = mqtt.Client()
# 设置回调函数
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
try:
# 连接到 MQTT 服务器
mqtt_client.connect(broker_address, port)
# 启动网络循环
mqtt_client.loop_forever()
except Exception as e:
logging.error(f"连接MQTT服务器时发生错误: {e}")
finally:
# 断开与 MQTT 服务器的连接
mqtt_client.disconnect()