# mqtt
MQTT( Message Queuing Telemetry Transport ,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的"轻量级"通讯协议,该协议构建于TCP/IP协议上。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。低开销、低带宽占用的即时通讯协议。
MQTT传输的消息分为:主题(Topic)和负载(payload)两部分:
- Topic,可以理解为消息的类型,订阅者订阅(Subscribe)后,就会收到该主题的消息内容(payload);
- payload,可以理解为消息的内容,是指订阅者具体要使用的内容。
配合strophe.min.js 地址 (opens new window)
<script src="./static/js/jquery-3.3.1.min.js"></script>
<script src="./static/js/strophe.min.js"></script>
# MQTT协议中的方法
- Connect。等待与服务器建立连接。
- Disconnect。等待MQTT客户端完成所做的工作,并与服务器断开TCP/IP会话。
- Subscribe。等待完成订阅。
- UnSubscribe。等待服务器取消客户端的一个或多个topics订阅。
- Publish。MQTT客户端发送消息请求,发送完成后返回应用程序线程。
<script
src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"
type="text/javascript">
</script>
<script>
var mqtt=null;
var reconnectTimeout = 3000;
var host = 'xx.xxxxx.com'; // hostname or IP address
var port = 80xx;
var topic = '';
var useTLS = false;
var username = null;
var password = null;
//false时保留消息,实现离线消息功能
var cleansession = false;
function MQTTconnect() {
try {
username = newThis&&newThis.$store.state.selfmes.landline||'';
password = "xxxxx";
clientId = newThis&&newThis.$store.state.selfmes.landline;
mqtt = new Paho.MQTT.Client(
host,
port,
clientId);
var options = {
timeout: 3,
useSSL: useTLS,
cleanSession: cleansession,
onSuccess: onConnect,
onFailure: function (message) {
newThis&&newThis.$message.error(
`连接失败,请稍后再试,报错信息为:${message.errorMessage}`
)
// $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
if (username != null) {
options.userName = username;
options.password = password;
}
mqtt.connect(options);
} catch (error) {
console.log('mqtt登录后再连接')
}
}
function onConnect() {
topic=`/aaaaa/${newThis.$store.state.selfmes.landline}`
mqtt.subscribe(topic, {qos: 2});
}
function onConnectionLost(response) {
console.log(response.errorMessage)
setTimeout(MQTTconnect, reconnectTimeout);
};
//收到回复消息或者是告知发送消息成功了!
function onMessageArrived(message) {
//拿到发送消息接受体
// var payload =JSON.parse(message.payloadString)
var temhtml;
try {
temhtml=JSON.parse(message.payloadString);
} catch (error) {
temhtml=message.payloadString;
return;
}
let getmes=temhtml.content;
......
};
</script>
let sendmes={
chatType:1,
content:this.qqtext,
from:that.$store.state.selfmes.landline,
contentType:0,
groupJid:this.qqroomid,
to: that.qqlandline,
groupName:that.qqtopic,
timeStamp:new Date().getTime(),
name:that.$store.state.selfmes.name,
photo:that.$store.state.selfmes.photo,
}
sendmes= JSON.stringify(sendmes)
console.log(sendmes)
let msg = $msg({
to: "receiver@wx.cintelcloud.com",
from: that.$store.state.selfmes.jid,
type: 'chat'
}).c("body", null, sendmes);
qconnection.send(msg.tree())