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("模拟数据上报关闭!!!");
}
相关推荐
程序猿乐锅2 小时前
从0-1一文详解RabbitMQ
java·分布式·后端·中间件·rabbitmq·ruby
考虑考虑5 小时前
JDK26中的List.ofLazy()
java·后端·java ee
小蒜学长5 小时前
基于SpringBoot的公寓报修管理系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·公寓报修管理系统·多角色协同
云浪6 小时前
Go源码分析:搞懂 Go 是如何实现堆的
后端·go·源码阅读
用户033307413959 小时前
TypeScript using 与 AsyncDisposableStack:在真实服务端代码中协调多资源清理
前端
daisychey9 小时前
用 Playwright 做多平台内容分发,我踩过的 8 个坑
前端
调试人生的显微镜9 小时前
iOS开发入门:Interface Builder、基础控件及UITextField详解
后端·ios
泡海椒9 小时前
巡检照片与工单附件:jquick-pdf 图片嵌入的业务实战
后端
蜗牛互联网9 小时前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
AI持续学习9 小时前
文档权限变更如何回归测试?账号、空间、文件和分享链接用例清单
后端