const mqtt = require('mqtt') //import mqtt from 'mqtt' // 连接选项 const options = { clean: true, // 保留回话 connectTimeout: 4000, // 超时时间 // 认证信息 clientId: 'emqx_test', username: 'XXX', //必须在mqtt关闭匿名才会起作用 password: 'XXX', } // 连接字符串, 通过协议指定使用的连接方式 // ws 未加密 WebSocket 连接 // wss 加密 WebSocket 连接 // mqtt 未加密 TCP 连接 // mqtts 加密 TCP 连接 // wxs 微信小程序连接 // alis 支付宝小程序连接 //const connectUrl = 'wss://broker.emqx.io:8084/mqtt' const connectUrl = 'mqtt://XX.XX.XXX.XXX:1883/mqtt' const client = mqtt.connect(connectUrl, options) client.subscribe('qi',{qos:1});//订阅主题为test的消息 client.publish("qi","nodejs"); client.on('reconnect', (error) => { console.log('正在重连:', error) }) client.on('error', (error) => { console.log('连接失败:', error) }) client.on('message', (topic, message) => { console.log('收到消息:', topic, message.toString()) })