前端调用(mqtt协议)
简单介绍下mqtt他就是和websocket基本类似,但实质上还是不同的(这个可以查阅更准确的内容)
这个js用在react还是vue中没有实质的区别都是类似了,以下的代码我用在了react中
mqtt协议主要流程
1.是先要链接
2.通过订阅消息,也就是说根据接口发送消息
3.后台回实时传输数据
这里要注意,当你想要订阅下一个消息的时候,你需要取消订阅上一个消息
这里我用的是paho-mqtt这个模块,个人感觉还是比较好用的。基本信息了解了直接上代码
var hostname = 'xxx.xxx.xxx.xxx',//这里就是ip
port = 1883,//端口
clientId = Math.random().toString(36).substr(2),//这个id一般是要传给后台的,都设置成随机数
timeout = 5,//这个是多久算超时,也可以不加
keepAlive = 100,
userName = 'test',//这个后端会给你个用户名和密码
password = 'test',//这个后端会给你个用户名和密码
topicOnePre = 'SpeedRegulation/CompayInfo',//这个就是你要订阅的主题也就是后台给的接口
topicOne = '',
clientIDOne = Math.random().toString(36).substr(2),
clientIDTwo = Math.random().toString(36).substr(2),
topicTwoPre = 'SpeedRegulation/SiteInfo',//因为订阅主题不只是一个可能订阅这个后还要订阅下一个
topicTwo = ''
client = new PahoMQTT.Client(hostname, port, clientId);
client.connect({
invocationContext: {//是一些链接mqtt的基本配置
host: hostname,
port: port,
path: client.path,
clientId: clientId
},
timeout: timeout,
keepAliveInterval: keepAlive,
onSuccess: onConnect,//这个是链接成功的回调函数
reconnect: true,
onFailure: function (e) { }
})
function onConnect() {
console.log("onConnected");
var sendMess = {//这是你要传给后端的值,也就是发布主题的时候传参
Time: new Date().getTime(),
}
message = new PahoMQTT.Message(JSON.stringify(sendMess));
message.destinationName = topicOnePre;//发送消息的主题
client.send(message);//发送消息
topicOne = topicOnePre + '/' + clientIDOne;//因为订阅新主题的时候后端不可能用一样的主题,所以要在主题后加一段字符串或者数字来识别,例如:clientIDOne
client.subscribe(topicOne)//订阅主题
}
client.onConnectionLost = this.onConnectionLost;
client.onMessageArrived = this.onMessageArrived;
function onConnectionLost(responseObject) {//订阅失败
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
console.log("连接已断开");
}
}
function onMessageArrived(message) {//订阅成功后会返回消息
var objResult = JSON.parse(message.payloadString);//这个就是后台反给前端的消息
}
//以上订阅第一个就完成了,紧接着订阅第二个。这时候你要注意,必须取消第一个订阅才可以
var sendMess = {
Time: new Date().getTime(),
ClientID: clientIDTwo
}
message = new PahoMQTT.Message(JSON.stringify(sendMess));
message.destinationName = topicTwoPre;
client.send(message);
// 2屏订阅
topicTwo = topicTwoPre + '/' + clientIDTwo
client.unsubscribe(topicOne)//取消第一主题个订阅
client.subscribe(topicTwo)//订阅第二个主题
client.onConnectionLost = function(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
console.log("连接已断开");
}
}
client.onMessageArrived = (message)=>{
let temp = JSON.parse(message.payloadString)
};
以上就是我对mqtt的理解和使用了