uniapp app 如何集成mqtt实现实时通信
在uniapp开发的app中,如何集成mqtt协议来实现实时通信?需要具体步骤或推荐可用的mqtt插件,谢谢!
2 回复
在uniapp中集成MQTT实现实时通信,推荐使用mqtt.js库。步骤如下:
- 安装:
npm install mqtt - 引入:
import mqtt from 'mqtt' - 连接:
const client = mqtt.connect('mqtt://broker地址') - 订阅:
client.subscribe('主题') - 发布:
client.publish('主题', '消息') - 监听消息:
client.on('message', 回调函数)
注意:H5端可直接使用,App端需配置网络权限。
在 UniApp 中集成 MQTT 实现实时通信,可通过以下步骤完成。推荐使用 mqtt.js 库,它支持 WebSocket 协议,适用于 UniApp 的 H5 和小程序环境。
步骤:
-
安装 MQTT 库
在项目根目录执行:npm install mqtt --save -
引入 MQTT
在页面或组件中导入:import mqtt from 'mqtt/dist/mqtt'; -
连接 MQTT 代理服务器
使用 WebSocket 连接(确保代理服务器支持 WS):const client = mqtt.connect('ws://your-mqtt-broker:port', { clientId: 'uniap-client-' + Math.random().toString(16), username: 'your-username', // 如果需要认证 password: 'your-password' }); -
处理连接和消息
client.on('connect', () => { console.log('MQTT 连接成功'); client.subscribe('your/topic', (err) => { if (!err) console.log('订阅主题成功'); }); }); client.on('message', (topic, message) => { console.log(`收到主题 ${topic} 的消息: ${message.toString()}`); // 处理接收到的消息,例如更新页面数据 }); client.on('error', (err) => { console.error('MQTT 错误:', err); }); -
发布消息
client.publish('your/topic', 'Hello MQTT from UniApp'); -
断开连接
在页面卸载或不需要时断开:client.end();
注意事项:
- 代理服务器:确保 MQTT 代理(如 Mosquitto、EMQX)支持 WebSocket,并配置正确的 WS 端口。
- 平台差异:
- H5:直接使用
mqtt.js。 - 小程序:需在微信开发者工具中开启“不校验合法域名”测试,或配置服务器域名到白名单。
- App:使用条件编译,通过
uni.connectSocket实现(需自行封装 MQTT 逻辑,或使用原生插件)。
- H5:直接使用
- 安全:生产环境使用
wss://(WebSocket Secure)加密连接。
示例代码(Vue 页面):
<template>
<view>
<button @click="publishMsg">发送消息</button>
</view>
</template>
<script>
import mqtt from 'mqtt/dist/mqtt';
export default {
data() {
return {
client: null
};
},
mounted() {
this.client = mqtt.connect('ws://test.mosquitto.org:8080');
this.client.on('connect', () => {
this.client.subscribe('uniapp/test');
});
this.client.on('message', (topic, message) => {
uni.showToast({ title: `收到: ${message}`, icon: 'none' });
});
},
methods: {
publishMsg() {
this.client.publish('uniapp/test', 'Hello from UniApp');
}
},
beforeDestroy() {
this.client?.end();
}
};
</script>
可能遇到的问题:
- 连接失败:检查代理地址、网络防火墙或认证信息。
- 小程序限制:需在
mp-weixin的app.json中配置"requiredPrivateInfos": ["connectSocket"]。
通过以上步骤,即可在 UniApp 中实现 MQTT 实时通信。根据实际需求调整主题和消息处理逻辑。

