发布主题test
pushmqtt.py
#!/bin/python312 import paho.mqtt.client as mqtt import time # MQTT代理服务器地址和端口 broker = 'ddoss.cn' port = 1883 # MQTT代理的默认端口 # 创建MQTT客户端实例 client = mqtt.Client() # 设置用户名和密码 client.username_pw_set(username='test', password='000000') # 定义连接成功的回调函数 def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker successfully.") else: print("Failed to connect, return code %d\n", rc) # 设置回调函数 client.on_connect = on_connect # 连接到MQTT代理 client.connect(broker, port) # 启动循环,处理网络事件 client.loop_start() # 定义要发布的消息和主题 topic = "test" try: while True: # 无限循环接收用户输入 # 提示用户输入消息 message = input("Enter the message to publish (or type 'exit' to quit): ") # 检查用户是否输入了退出命令 if message.lower() == 'exit': print("Exiting the message publisher.") break # 发布用户输入的消息到主题'test' client.publish(topic, message) print(f"Message published to topic '{topic}'") # 可选:加入适当的延迟,避免过快地发布消息 time.sleep(1) # 一秒的延迟 except KeyboardInterrupt: # 处理用户中断(如Ctrl+C) print("\nMessage publisher interrupted by user.") finally: # 停止循环 client.loop_stop() print("Disconnected from MQTT Broker")
订阅主题:pullmqtt.py
#!/bin/python312 import paho.mqtt.client as mqtt import time # 导入time模块,用于time.sleep() # MQTT代理服务器地址和端口 broker = 'ddoss.cn' port = 1883 # MQTT代理的默认端口 # 创建MQTT客户端实例 client = mqtt.Client() # 设置用户名和密码 client.username_pw_set(username='test', password='000000') # 定义连接成功的回调函数 def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker successfully.") # 连接成功后订阅主题 client.subscribe("test", qos=1) # 设置QoS等级 else: print("Failed to connect, return code %d\n", rc) # 定义消息到达的回调函数 def on_message(client, userdata, msg): print(f"Received message '{msg.payload.decode()}' on topic '{msg.topic}'") # 设置回调函数 client.on_connect = on_connect client.on_message = on_message # 连接到MQTT代理 client.connect(broker, port) # 启动循环,处理网络事件 client.loop_start() try: # 保持主线程运行,直到手动停止或接收到退出信号 while True: time.sleep(1) except KeyboardInterrupt: # 处理用户中断(如Ctrl+C) print("\nSubscription interrupted by user.") finally: # 停止循环 client.loop_stop() print("Disconnected from MQTT Broker")
Powered by ddoss.cn 12.0
©2015 - 2024 ddoss
渝公网安备50011302222260号 渝ICP备2024035333号 【实验平台安全承诺书】 小绿叶技术社区,优化网络中,点击查看配置信息
您的IP:192.168.122.82,2024-10-10 18:14:11,Processed in 0.02417 second(s).