代码实现一个线程与mqtt服务器联系
时间: 2024-01-02 07:03:02 浏览: 131
以下是使用Python paho-mqtt库实现线程与MQTT服务器联系的代码示例:
```python
import threading
import paho.mqtt.client as mqtt
# MQTT服务器地址和端口号
MQTT_SERVER = "localhost"
MQTT_PORT = 1883
# MQTT订阅主题
MQTT_TOPIC = "/test"
# 线程类
class MyThread(threading.Thread):
def __init__(self, thread_id, name, client):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.client = client
def run(self):
print(f"Starting {self.name}")
# 发布消息
self.client.publish(MQTT_TOPIC, f"Hello from {self.name}")
print(f"Exiting {self.name}")
# MQTT连接回调函数
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# 订阅主题
client.subscribe(MQTT_TOPIC)
# MQTT消息接收回调函数
def on_message(client, userdata, msg):
print(f"Received message: {msg.payload.decode('utf-8')}")
if __name__ == "__main__":
# 创建MQTT客户端实例
client = mqtt.Client()
# 设置连接回调函数和消息接收回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接MQTT服务器
client.connect(MQTT_SERVER, MQTT_PORT, 60)
# 启动线程
thread1 = MyThread(1, "Thread-1", client)
thread2 = MyThread(2, "Thread-2", client)
thread1.start()
thread2.start()
```
这个示例中,我们创建了一个MyThread线程类,并在run方法中实现了向MQTT服务器发布消息的逻辑。在主程序中,我们创建了两个线程,分别启动这两个线程。在连接MQTT服务器后,我们订阅了一个主题,当收到该主题的消息时,会触发on_message回调函数。
阅读全文