其他:https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
这些Broker/Server已经搭建好了,只需要编写Client/Subscriber就能测试一下MQTT了。
以使用Python的paho-mqtt来实现客户端。连接test.mosquitto.org服务为例。
(1)安装Eclipse Paho客户端
pip install paho-mqtt
(2)客户端连接
unencrypted-mqtt.py
# coding=utf8 import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("test/rensanning/time") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("test.mosquitto.org", 1883) client.loop_forever()
执行 python unencrypted-mqtt.py
(2)发布消息
pub-mqtt.py
# coding=utf8 import paho.mqtt.client as mqtt import time def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("test.mosquitto.org", 1883) while client.loop() == 0: msg = "test message from Publisher "+time.ctime() client.publish("test/rensanning/time", msg, 0, True) print("message published") time.sleep(1.5) pass
执行 python pub-mqtt.py
(3)订阅消息
sub-mqtt.py
# coding=utf8 import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("test/rensanning/time") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("test.mosquitto.org", 1883) client.loop_forever()
执行 python sub-mqtt.py
同时运行订阅和发布客户端。
加密通信,访问8883端口
先从 http://test.mosquitto.org/ 下载 mosquitto.org.crt文件。
pub-mqtt-tls.py
# coding=utf8 import paho.mqtt.client as mqtt import time def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.tls_set("mosquitto.org.crt") client.connect("test.mosquitto.org", 8883) while client.loop() == 0: msg = "test message from Publisher "+time.ctime() client.publish("test/rensanning/time", msg, 0, True) print("message published") time.sleep(1.5) pass
执行 python pub-mqtt-tls.py