1,安装服务端 mosquitto
apt-get install mosquitto
2,安装客户端paho.mqtt.python
pip install paho-mqtt
3, mqtt 应用在ubuntu上
import paho.mqtt.client as mqtt
import time
HOST="127.0.0.1"//mosquitto 安装的主机ip,127.0.0.1 表示与mosquitto在同一机器上
PORT=1883
client=mqtt.Client()
def on_connect(client,userdata,msg):
print("on_connect")
pass
def on_dis_connect(client,userdata,msg):
print("on_dis_connect")
pass
def mqtt_sub(topic):
client.subscribe(topic,1)
def mqtt_pub(topic,payload):
client.publish(topic,payload,1,1)
def mqtt_init(on_message):
client.connect(HOST,PORT,60)
client.on_connect=on_connect
client.on_disconnect=on_dis_connect
client.on_message = on_message
client.loop_start()
def on_message(client,userdata,msg):
print(msg.topic+":+"+str(msg.payload))//如果有人发布订阅,这个地方接收订阅
if __name__=='__main__':
mqtt_init(on_message):
mqtt_sub("/device/+/upgrade")//订阅一个topic
while True:
time.sleep(10)
4,MQTTBox
一个window端的mqtt客户端。可以配合着上面的程序进行测试。
配置界面,其中host填上mosquitto 所在主机,协议mqtt/tcp 其他的不用太关心
发布topic界面