基于vue写长连接

1、下载MQTT “npm install mqtt”

	也可以直接将{"mqtt": "^4.2.6",}放到package.json中,然后执行npm install

2、emqx.js文件,引入mqtt,及相关事件

import MQTT from 'mqtt'
const mqttId = Math.random().toString(36).substr(2);
const topicList = {};
//username password 为连接的后台用户及密码
const option = {
  clean: true,
  connectTimeout: 4000,
  clientId: mqttId,
  username: 'admin',
  password: '123456'
}

const connectUrl = 'ws://192.168.0.161:9999/mqtt';//此为连接的后台地址
const emqx = MQTT.connect(connectUrl, option);

emqx.on('connect', () => {
  console.log('mqtt服务器连接成功', connectUrl);
}).on('error', (err) => [
  console.log('MQTT连接失败,出现异常:', err)
]).on('message', (topic, payload) => {
  let msgJson = JSON.parse(payload);
  if(!topicList[topic]) return;
  topicList[topic](msgJson);
})

emqx.subscribeTopic = function(topic, callback) {
  if(typeof(topic) !== 'string' || typeof(callback) !== 'function') {
    console.log('输入的话题或者回调函数格式不正确');
    return;
  }
  emqx.subscribe(topic);
  topicList[topic] = callback;
}

export {
  emqx
}

3、页面中使用

import { emqx } from "@/api/emqx";
//message为后端定的各种事件名,前端订阅,进而获取对应的数据
emqx.subscribeTopic('message', data=> {
      console.log(data,'后端传来的数据')
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值