第17章 Mosquitto WebSocket支持

第17章 WebSocket支持

17.1 WebSocket over MQTT

WebSocket
TCP/MQTT
浏览器
Mosquitto
原生客户端
协议转换
WebSocket帧
MQTT报文

17.2 配置WebSocket

bash 复制代码
# /etc/mosquitto/mosquitto.conf

# MQTT监听器
listener 1883
protocol mqtt

# WebSocket监听器
listener 9001
protocol websockets
allow_anonymous true

# 或者需要认证
listener 9001
protocol websockets
allow_anonymous false
password_file /etc/mosquitto/passwd

17.3 Web客户端实现

HTML示例

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>MQTT Web Client</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
    <h1>MQTT Dashboard</h1>
    <div>
        <input type="text" id="topic" placeholder="Topic">
        <input type="text" id="message" placeholder="Message">
        <button onclick="publish()">Publish</button>
    </div>
    <div id="output"></div>

    <script>
        const client = mqtt.connect('ws://localhost:9001');

        client.on('connect', () => {
            console.log('Connected');
            client.subscribe('sensor/#');
        });

        client.on('message', (topic, message) => {
            const output = document.getElementById('output');
            output.innerHTML += `<p>${topic}: ${message}</p>`;
        });

        function publish() {
            const topic = document.getElementById('topic').value;
            const message = document.getElementById('message').value;
            client.publish(topic, message);
        }
    </script>
</body>
</html>

Vue.js示例

vue 复制代码
<template>
  <div>
    <h1>MQTT Monitor</h1>
    <div v-for="(msg, index) in messages" :key="index">
      {{ 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();
  }
};
</script>

17.4 跨域配置

bash 复制代码
# 需要反向代理处理跨域

# Nginx配置
location /mqtt {
    proxy_pass http://localhost:9001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

17.5 实时应用案例

传感器
Mosquitto
WebSocket客户端
原生客户端
Web仪表板
实时图表
地图监控

17.6 本章小结

掌握了Mosquitto的WebSocket配置和Web客户端开发。

相关推荐
迪康Defender1 小时前
AI 重构终端安全运营:智能分析中枢 AI Insight 模块架构与落地场景深度解析
运维·网络·人工智能·其他·安全·重构·架构
0x532 小时前
Java网络编程(二)
java·服务器·网络
AI领路人.2 小时前
[特殊字符] 用 OpenClaw 实现一个 C++ 复刻版 QuantClaw
websocket·单元测试·discord·rest api·内存占用·c++17
微硬创新2 小时前
老旧产线改造:耐达讯自动化16路4‑20mA转PROFINET的工程实践
人工智能·网络协议·自动化·信息与通信
西安景驰电子4 小时前
《PTP精确时间协议系列》第一篇:从原理到应用,全面解读IEEE 1588
linux·运维·服务器·开发语言·网络·windows·php
ZGi.ai4 小时前
多模型回答不稳定:路由规则与评测方法
网络·人工智能·大模型评测·多模型·模型路由·zgi·模型网关
80s7775 小时前
独享住宅IP、长效代理ip是什么?有哪些作用?
网络·网络协议·tcp/ip
IPdodo_5 小时前
静态 IP、住宅 IP 和固定出口有什么区别?开发场景选型指南
服务器·网络·网络协议·tcp/ip·代理ip
_ZHOURUI_H_6 小时前
Unity TCP底层极限拆解:粘包、半包、CRC、序列号、双缓冲到底怎么一起工作的?
网络·网络协议·tcp/ip·游戏·unity·游戏引擎·游戏开发
长江&后浪7 小时前
防火墙的描述
开发语言·网络·php