第17章 Mosquitto WebSocket支持

张开发
2026/4/11 11:58:00 15 分钟阅读

分享文章

第17章 Mosquitto WebSocket支持
第17章 WebSocket支持17.1 WebSocket over MQTTWebSocketTCP/MQTT浏览器Mosquitto原生客户端协议转换WebSocket帧MQTT报文17.2 配置WebSocket# /etc/mosquitto/mosquitto.conf# MQTT监听器listener1883protocol mqtt# WebSocket监听器listener9001protocol websockets allow_anonymoustrue# 或者需要认证listener9001protocol websockets allow_anonymousfalsepassword_file /etc/mosquitto/passwd17.3 Web客户端实现HTML示例!DOCTYPEhtmlhtmlheadtitleMQTT Web Client/titlescriptsrchttps://unpkg.com/mqtt/dist/mqtt.min.js/script/headbodyh1MQTT Dashboard/h1divinputtypetextidtopicplaceholderTopicinputtypetextidmessageplaceholderMessagebuttononclickpublish()Publish/button/divdividoutput/divscriptconstclientmqtt.connect(ws://localhost:9001);client.on(connect,(){console.log(Connected);client.subscribe(sensor/#);});client.on(message,(topic,message){constoutputdocument.getElementById(output);output.innerHTMLp${topic}:${message}/p;});functionpublish(){consttopicdocument.getElementById(topic).value;constmessagedocument.getElementById(message).value;client.publish(topic,message);}/script/body/htmlVue.js示例template div h1MQTT Monitor/h1 div v-for(msg, index) in messages :keyindex {{ msg.topic }}: {{ msg.payload }} /div /div /template script import mqtt from mqtt; export default { data() { return { client: null, messages: [] }; }, mounted() { this.client mqtt.connect(ws://localhost:9001); this.client.on(connect, () { this.client.subscribe(sensor/#); }); this.client.on(message, (topic, message) { this.messages.push({ topic, payload: message.toString() }); }); }, beforeUnmount() { this.client.end(); } }; /script17.4 跨域配置# 需要反向代理处理跨域# Nginx配置location /mqtt{proxy_pass http://localhost:9001;proxy_http_version1.1;proxy_set_header Upgrade$http_upgrade;proxy_set_header Connectionupgrade;proxy_set_header Host$host;proxy_set_header X-Real-IP$remote_addr;}17.5 实时应用案例传感器MosquittoWebSocket客户端原生客户端Web仪表板实时图表地图监控17.6 本章小结掌握了Mosquitto的WebSocket配置和Web客户端开发。

更多文章