python 实现简单的 MQTT 协议收发
安装 MQTT Broker
- mosquitto 纯 C 实现
- https://github.com/eclipse/mosquitto.git
安装
brew install mosquitto
启动服务
mosquitto
接受 消息
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("test/topic")
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
if __name__ == '__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 60)
client.loop_forever()
发送消息
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.publish("test/topic", "Connect, MQTT!")
if __name__ == '__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.connect("127.0.0.1", 1883, 60)
client.loop_start()
while True:
client.publish("test/topic", "Hello, MQTT!")
time.sleep(10)
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17672513.html