第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客户端开发。

相关推荐
酣大智8 分钟前
华为 VRRP的抢占延迟时间
网络·tcp/ip·vrrp
hengmeida40 分钟前
楼宇控制柜标准化项目交付完整规范
大数据·网络·笔记
2501_9378609442 分钟前
上篇:网络编程基础与UDP套接字编程
java·网络·计算机网络
烟雨江南7851 小时前
会议语音识别私有化部署方案:音频不出内网,如何接入现有会议系统
人工智能·websocket·音视频·语音识别·ai客服
那年窗外下的雪.1 小时前
AIDC 学习日志|第 27 天|EVPN 多归属收敛时间线与 Leaf2 接管验证
网络协议·学习·http·tcpdump
xixiaoyunya1 小时前
制造业生产数据备份:在“不停产“前提下的自动化实践
网络·安全
Figo_Cheung1 小时前
Figo权重动力学:递归本体论与跨尺度演化的形式化基础——揭示:宇宙的演化,本质上就是一场由无数观测者共同参与的、永不停歇的、跨尺度的权重重构盛宴。
网络·人工智能·量子计算
j7~2 小时前
【Linux】三十八.C++ 手写 HTTP 服务器:裸 socket + fork 多进程,从 HTTP 报文解析到浏览器打开网页
linux·网络·网络协议·学习·http·网络编程
FW-Linker2 小时前
偏远山区户外直播网络优化:多链路聚合如何保障稳定低时延传输
网络·5g·智能路由器
小则又沐风a3 小时前
深入理解TCP协议----滑动窗口,流量控制
linux·网络协议·tcp