几点说明
MQTT over TCP:
监听端口:1883
用于传统的 MQTT 客户端,通过 TCP 进行通信。
配置了基本的代理参数,如超时和缓冲区大小。MQTT over SSL/TLS:
监听端口:8883
用于需要加密通信的 MQTT 客户端。
配置了 SSL 证书和私钥路径。MQTT over WebSocket:
监听端口:80
用于通过 WebSocket 进行通信的 MQTT 客户端,适用于需要穿越防火墙或在浏览器中使用的场景。
配置了 WebSocket 协议的升级头。MQTT over Secure WebSocket (WSS):
监听端口:443
用于通过加密的 WebSocket 进行通信的 MQTT 客户端。
配置了 SSL 证书和私钥路径,并启用了加密协议。
安装mosquitto
version: '3'services:my-python-app:image: helloproj_my-python-appexpose:- "5000" # 暴露给同一网络中的其他容器networks:- app-networknginx:image: nginx:latestvolumes:- ./nginx.conf:/etc/nginx/nginx.conf # 挂载配置文件- ./key:/etc/nginx/ssl # 挂载 SSL 证书ports:- "80:80" # 将容器的80端口映射到主机的80端口- "443:443" # HTTPS- "1883:1883"depends_on:- my-python-app # 确保 Flask 容器启动后再启动 Nginx- mosquittonetworks:- app-networkmosquitto:image: eclipse-mosquitto:latestcontainer_name: mosquittoexpose:- "1883"volumes:- ./mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf- ./mosquitto/data:/mosquitto/data- ./mosquitto/log:/mosquitto/log networks:- app-networknetworks:app-network:driver: bridge
配置nginx
stream {upstream mqtt_backend {server mosquitto:1883;}server {listen 1883;proxy_pass mqtt_backend;}
}
编写代码
import paho.mqtt.client as mqtt# 收到消息时调用
def on_message(client, userdata, msg):print(f"Received message: {msg.payload.decode()} on topic: {msg.topic}")# 连接成功时调用
def on_connect(client, userdata, flags, rc, properties=None):print(f"Connected with result code {rc}")# 订阅特定主题client.subscribe("test/topic")# 创建 MQTT 客户端实例
client = mqtt.Client()# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message# 连接到 MQTT Broker
client.connect("x.x.x.x", 1883, 60)# 开始网络循环
client.loop_forever()
import paho.mqtt.client as mqtt# 连接成功时调用
def on_connect(client, userdata, flags, rc):print(f"Connected with result code {rc}")# 发布消息client.publish("test/topic", "Hello MQTT!")# 创建 MQTT 客户端实例
client = mqtt.Client()
client.on_connect = on_connect# 连接到 MQTT Broker
client.connect("x.x.x.x", 1883, 60)# 开始网络循环,处理所有网络流量
client.loop_start()# 发布频率(秒)
import time
time.sleep(1)# 停止网络循环
client.loop_stop()
增加权限控制
persistence true
persistence_location /mosquitto/data
log_dest file /mosquitto/log/mosquitto.log
# 增加以下两个文件
password_file /mosquitto/config/pwdfile
acl_file /mosquitto/config/aclfile# 修改这里
allow_anonymous false
listener 1883
- 进到容器内部添加password_file和acl_file
docker exec -it mosquitto /bin/shtouch pwdfile
mosquitto_passwd -b pwdfile chenph 123456chmod 0700 pwdfile#### aclfile文件 ####
user chenph
topic read topic/#
topic write topic/#chmod 0700 aclfile# 重启一下
docker-compose restart mosquitto# docker-compose.yml 也调整一下,重构一下容器
volumes:- ./mosquitto/config:/mosquitto/config # 改成这样- ./mosquitto/data:/mosquitto/data- ./mosquitto/log:/mosquitto/log
# 在连接之前,增加这个代码,成功的话会返回code 0,权限异常的话会返回5
client.username_pw_set("chenph", "123456")# 别忘了把主题名字改了,在acl中配置了只允许topic/#
client.publish("topic/test", "Hello MQTT!")