1. 下载Docker镜像
dockerpullemqx/emqx
2. 后台运行镜像
dockerrun-dit--nameemqx-p18083:18083-p1883:1883-p8083:8083-p8084:8084emqx/emqx:latest
3. 进入emqx的docker 命令
dockerexec-itemqx/bin/sh
4.访问emqt的web管理页面
- http://127.0.0.1:18083
- #账号: admin
- #密码: public
5.端口
- 1883:MQTT 协议端口
- 8883:MQTT/SSL 端口
- 8083:MQTT/WebSocket 端口
- 8080:HTTP API 端口
- 18083:Dashboard 管理控制台端口
6.python 链接mqtt 创建发布端
# python 3.6importrandomimporttimefrompaho.mqttimportclientasmqtt_clientbroker='127.0.0.1'port=1883topic="林中静月下仙"# generate client ID with pub prefix randomlyclient_id=f'python-mqtt-{random.randint(0, 1000)}'defconnect_mqtt(): defon_connect(client, userdata, flags, rc): ifrc==0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client=mqtt_client.Client(client_id) client.on_connect=on_connectclient.connect(broker, port) returnclientdefpublish(client): msg_count=0whileTrue: time.sleep(1) msg=f"messages: {msg_count}"result=client.publish(topic, msg) # result: [0, 1]status=result[0] ifstatus==0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}") msg_count+=1defrun(): client=connect_mqtt() client.loop_start() publish(client) if__name__=='__main__': run()
ConnectedtoMQTTBroker!Send `messages: 0` totopic `林中静月下仙` Send `messages: 1` totopic `林中静月下仙` Send `messages: 2` totopic `林中静月下仙` Send `messages: 3` totopic `林中静月下仙`
7.python 链接mqtt 创建订阅端
# python3.6importrandomfrompaho.mqttimportclientasmqtt_clientbroker='127.0.0.1'port=1883topic="林中静月下仙"# generate client ID with pub prefix randomlyclient_id=f'python-mqtt-{random.randint(0, 100)}'defconnect_mqtt() ->mqtt_client: defon_connect(client, userdata, flags, rc): ifrc==0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client=mqtt_client.Client(client_id) client.on_connect=on_connectclient.connect(broker, port) returnclientdefsubscribe(client: mqtt_client): defon_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") client.subscribe(topic) client.on_message=on_messagedefrun(): client=connect_mqtt() subscribe(client) client.loop_forever() if__name__=='__main__': run()
ConnectedtoMQTTBroker!Received `messages: 12` from `林中静月下仙` topicReceived `messages: 13` from `林中静月下仙` topicReceived `messages: 14` from `林中静月下仙` topicReceived `messages: 15` from `林中静月下仙` topic