1、 脚本安装
curl https://repos.emqx.io/install_emqx.sh | bash
2、 docker安装
(1)先把emqx 里面得配置文件复制出来
docker cp emqx:/opt/emqx $PWD/emqx
docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8883:8883 -p 8084:8084 -p 18083:18083 -v $PWD/emqx:/opt/emqx emqx/emqx:v4.0.0
2、 使用python使用mqtt 。 发布者、订阅者都是属于客户端。
import paho.mqtt.client as mqtt
import time
a = 0
def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))
def on_demo1_msg(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
# 发送给demo2
time.sleep(1)
client.publish("demo2", payload="hello, i am demo1")
def on_demo2_msg(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
# 发送给demo2
time.sleep(1)
client.publish("demo1", payload="hello, i am demo2")
global a
a += 1
if a==10:
client.disconnect()
def on_disconnect(client, userdata, rc):
print("disconnect, ", str(rc))
client = mqtt.Client() # 实例化客户端
client.on_connect = on_connect 客户端连接回调函数(触发)
# client.on_message这个的升级版? 可以触发多个接受函数。
client.message_callback_add("demo1", on_demo1_msg) 接受主题的触发函数
client.message_callback_add("demo2", on_demo2_msg)
client.on_disconnect = on_disconnect # 关闭客户端的回调汉书
client.connect('127.0.0.1', 1883, 600) # 600为keepalive的时间间隔
client.subscribe('demo1', qos=0) # 订阅主题
client.subscribe('demo2', qos=0) # 订阅主题
client.publish("demo1", payload="hello, begin the loop") # 发布消息
client.loop_forever() # 保持连接