一谈论到这玩意可能很多前端很懵?这玩意是啥我从来没接触过?其实这是一个物联网的协议,可能只有做物联网的项目才能接触,而且资料不是很多最全的还是官方文档,下面做一个官方的介绍吧
MQTT是机器对机器(M2M)/物联网(IoT)连接协议。它被设计为一个极其轻量级的发布/订阅消息传输协议。对于需要较小代码占用空间和/或网络带宽非常宝贵的远程连接非常有用,是专为受限设备和低带宽、高延迟或不可靠的网络而设计。这些原则也使该协议成为新兴的“机器到机器”(M2M)或物联网(IoT)世界的连接设备,以及带宽和电池功率非常高的移动应用的理想选择。例如,它已被用于通过卫星链路与代理通信的传感器、与医疗服务提供者的拨号连接,以及一系列家庭自动化和小型设备场景。它也是移动应用的理想选择,因为它体积小,功耗低,数据包最小,并且可以有效地将信息分配给一个或多个接收器。
- 特点
- 开放消息协议,简单易实现
- 发布订阅模式,一对多消息发布
- 基于TCP/IP网络连接,提供有序,无损,双向连接。
- 1字节固定报头,2字节心跳报文,最小化传输开销和协议交换,有效减少网络流量。
- 消息QoS支持,可靠传输保证
其实对于我们项目来说,最重要的是前端后端都可以发遗嘱?遗嘱是什么呢?
简单的来说前端订阅后端主题进行连接那么后端可以发送消息给前端类似于websocket长连接,如果前端突然离线了,后端检测到了连接空闲时间超过了对应时间,服务端存储了前端的遗嘱那么就启用遗嘱,专业一点就是这样的来说
Keep Alive指定连接最大空闲时间T,当客户端检测到连接空闲时间超过T时,必须向Broker发送心跳报文PINGREQ,Broker收到心跳请求后返回心跳响应PINGRESP。若Broker超过1.5T时间没收到心跳请求则断开连接,并且投递遗嘱消息到订阅方;同样,若客户端超过一定时间仍没收到心跳响应PINGRESP则断开连接。
下面是代码:
// #ifdef H5
import mqtt from 'mqtt'
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
import mqtt from '../../node_modules/mqtt/dist/mqtt.min.js'
// #endif
function mqttRequest({
url,
port,
mac,
userName = "",
passWord = "",
payload
}) {
let agreement;
//1.协议
// #ifdef H5
agreement = "ws://"
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
agreement = "wx://"
// #endif
// 2.端口
url = `${agreement}${url}`;
console.log(url)
// 4.根据协议规则必须传递userName: 'admin',password: 'password',
let client = mqtt.connect(url, {
port: port,
username: userName,
clean: true, // 保留回话
// connectTimeout: 4000, // 超时时间
password: passWord,
mac: mac,
keepalive:10,
keepAliveInterval: 4, //心跳包
// timeout: 6, //超时时间
connectTimeout: 4000, // 超时时间
reconnect: true, //自动重连
will: {
topic: 'error',
payload: payload,
retain: false,
qos: 0,
},
})
return client
}
export {
mqttRequest
}
/*
client.on('connect', function() {
console.log('on connect');
连接成功就订阅主题
client.subscribe(["send","close","gg"]);
console.log('订阅成功');
client.on(message("reg","{msg:nihao}"))
function(err) {
if (!err) {
//发送
console.log("发送")
// client.publish('client', 'hello mqtt');
}
}
})
.on('reconnect', function() {
console.log('on reconnect');
})
.on('error', function(err) {
console.log(err)
console.log('on error');
})
.on('end', function() {
console.log('on end');
})
.on('message', function(topic, message) {
console.log("接受,topic:" + topic + ",消息内容:" + message)
})
.on('offline', function() {
client.publish('close', 'close mqtt');
});
*/
this.client
.on('connect', function() {
// 连接成功就订阅主题
that.client.subscribe([`topic/${mac}`, 'register'], function(err) {
if (!err) {
console.log('成功');
that.client.publish('register', JSON.stringify(param));
}
});
console.log('订阅成功:topic');
})
.on('reconnect', function() {
console.log('正在重新连接');
})
.on('error', function(err) {
console.log(err);
})
.on('message', function(topic, res) {
res =[res].join()
let data = JSON.parse(res);
if (data.code == 200 && topic == `topic/${that.mac}`) {
});