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("模拟数据上报关闭!!!");
}
相关推荐
程序员黑豆35 分钟前
使用AI编程开发鸿蒙应用:从环境搭建到实战示例
前端·harmonyos
郑州光合科技余经理3 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
程序员黑豆4 小时前
鸿蒙应用开发:一次开发多端部署之响应式布局完全指南
前端·harmonyos
小月土星4 小时前
2.0 React Router 前端路由深度解析:从传统后端路由到现代 SPA 的完整演进
前端
hboot6 小时前
AI工程师第六课 - RAG检索增强生成
后端·langchain·llm
mldong6 小时前
jeeflow:98KB 的工作流引擎长什么样
后端
badhope3388 小时前
当所有AI都在抄同一份作业:前端模板的趋同、困局与破局
前端·ai·ai编程·前端开发·tailwind·ui设计
光影少年8 小时前
RN的Fabric 渲染流程
运维·前端·javascript·react native·react.js·fabric
__zRainy__9 小时前
React开始:直接在网站中使用React.js
前端·react.js·前端框架
程序员cxuan9 小时前
速度太快了!本地可以跑 DeepSeek-V4-Flash 了
人工智能·后端·程序员