mqtt python的写法
时间: 2024-07-23 22:00:56 浏览: 129
MQTT (Message Queuing Telemetry Transport) 是一种轻量级的发布/订阅消息协议,常用于物联网(IoT)应用中。在Python中使用Paho-MQTT库可以方便地操作MQTT。以下是简单的Paho-MQTT客户端连接、订阅和发布消息的基本步骤:
1. 首先,你需要安装paho-mqtt库。如果还没有安装,可以使用pip安装:
```bash
pip install paho-mqtt
```
2. 连接到MQTT服务器:
```python
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
else:
print(f"Connection failed with result code {rc}")
client = mqtt.Client()
client.on_connect = on_connect
client.connect("your_broker_address", port=1883, keepalive=60)
# 保持循环,以便及时处理来自服务器的消息
client.loop_forever()
```
3. 订阅主题:
```python
def on_message(client, userdata, msg):
print(f"Received message on topic '{msg.topic}': {str(msg.payload)}")
client.subscribe("your_topic")
client.on_message = on_message
```
4. 发布消息:
```python
def publish_message(topic, payload):
client.publish(topic, payload)
publish_message("another_topic", "Hello World!")
```
5. 关闭连接:
```python
def on_disconnect(client, userdata, rc):
print("Disconnected from MQTT broker")
client.disconnect()
client.on_disconnect = on_disconnect
# 等待断开连接或者手动调用client.disconnect()关闭连接
```
阅读全文