mqtt 测试

mqtt 测试

docker部署开源 mqtt broker 【eclipse-mosquitto】

bash 复制代码
docker run -d \
  --name mqtt \
  -p 1883:1883 -p 9001:9001 -p 9883:9883 \
  -v ./mqtt.conf:/mosquitto/config/mosquitto.conf \
  eclipse-mosquitto

mqtt.conf 增加websocet监听

yaml 复制代码
# This is a Mosquitto configuration file that creates a listener on port 1883
# that allows unauthenticated access.
listener 1883
allow_anonymous true

listener 9883
protocol http_api
http_dir /usr/share/mosquitto/dashboard

# WebSocket 监听
listener 9001
protocol websockets

vue中使用mqtt库

  1. 安装mqtt依赖
bash 复制代码
npm install mqtt

注: vue3 bable.config.js 添加配置,否则启动报错

js 复制代码
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  // 新增plugins
  plugins: [
    '@babel/plugin-transform-private-methods'
  ]
}
  1. mqtt工具
js 复制代码
import mqtt from 'mqtt'

// 9001 是 broker开放的websocket端口
const MQTT_URL = 'ws://localhost:9001/mqtt'

let client = null

/**
 * 获取 MQTT 客户端(单例)
 */
export function getMqttClient(topic) {
  if (!client) {
    client = mqtt.connect(MQTT_URL, {
      clientId: `vue2_${Math.random().toString(16).slice(2)}`,
      clean: true,
      reconnectPeriod: 4000,
      connectTimeout: 5000
    })

    client.on('connect', () => {
      console.log('[MQTT] connected')
      
      client.subscribe(topic)
      console.log('subscribe: ', topic)
    })

    client.on('error', err => {
      console.error('[MQTT] error', err)
    })

    client.on('close', () => {
      console.log('[MQTT] disconnected')
    })
  }

  return client
}

java模拟设备上报数据

  1. 引用maven依赖
xml 复制代码
 <dependency>
     <groupId>org.eclipse.paho</groupId>
     <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
     <version>1.2.5</version>
</dependency>
  1. 上报数据
java 复制代码
public static void main(String[] args) throws MqttException, InterruptedException {
    String broker = "tcp://localhost:1883";
    String clientId = "java-device-001";
    String topic = "device/temp";

    MqttClient client = new MqttClient(broker, clientId);
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(true);

    client.connect(options);
    System.out.println("✅ Connected to MQTT Broker");

    // 模拟温度上报

    for (int i = 0; i < 50000; i++) {
        String payload = "{\"temp\": " + (20 + i) + "}";
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(1);
        client.publish(topic, message);
        System.out.println("📤 Published: " + payload);
        Thread.sleep(2000);
    }

    client.disconnect();
    client.close();
    System.out.println("模拟数据上报关闭!!!");
}
相关推荐
Cosolar33 分钟前
不收费、不加水印、数据归你:我做了个开源的在线简历工具
后端·面试·前端框架
米米商聊1 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
小蒜学长2 小时前
基于Spring Boot+Vue3的在线医疗咨询系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·在线问诊·在线医疗咨询系统
echome8882 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌2 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易2 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
每天一道题3 小时前
CAP、Raft 与多数派:分布式系统如何达成一致?
分布式·后端·微服务
前端的日常3 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师3 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么3 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析