Websocket接入 node环境 安装依赖 plaintext $ npm install mqtt save js代码示例 python const mqtt require('mqtt') const fs require('fs') // 连接选项 const options { host: '127.0.0.1', // MQTT服务器地址。填入您的mqtt实例绑定的公网ip地址 port: 8084, // 端口号 (MQTTS通常用8883,MQTT用1883,WS用8083,WSS用8084) path: '/mqtt', // WebSocket 路径参数 username: 'yourusername', // 用户名 password: 'yourpassword', // 密码 protocol: 'wss', // 协议: mqtt, mqtts, ws, wss rejectUnauthorized: false, // 如果需要禁用证书验证,如果使用wss协议,默认的服务端证书客户端需要开启该选项进行禁用证书验证 } // 创建客户端连接 const client mqtt.connect(options) // 连接事件处理 client.on('connect', () > { console.log('成功连接到MQTT服务器') // 订阅主题 client.subscribe('test/topic', (err) > { if (!err) { console.log('成功订阅主题: test/topic') // 发布消息 client.publish('test/topic', 'Hello MQTT!') } }) }) // 接收消息 client.on('message', (topic, message) > { console.log(收到消息 [${topic}]: ${message.toString()}) }) // 错误处理 client.on('error', (err) > { console.error('连接错误:', err) }) // 断开连接处理 client.on('close', () > { console.log('连接已关闭') }) 浏览器环境 html代码示例 python 浏览器 MQTT 客户端 body { fontfamily: Arial, sansserif; maxwidth: 800px; margin: 0 auto; padding: 20px; }