[写在前面]
官网:https://websocket.org
...等等再写...
[版本明细]
"vue": "2.6.10",
"vue-router": "3.0.6",
"vuex": "3.1.0"
"electron": "^13.6.9",
"electron-devtools-installer": "^3.1.0",
[vue.config.js]
mqtt内部使用 ES6+ 的语法,使用过程中可能存在无法解析的情况,导致项目启动报错,需要在‘vue.config.js’中增加配置 transpileDependencies: ["mqtt"]
Ps. transpileDependencies 是一个Vue CLI 的配置选项,用于制定需要被转译的依赖包。在Vue项目中,有些依赖包可能是用了ES6+的语法,而一些低版本的浏览器不支持这些语法,因此需要将这些依赖包转译成ES5语法,以便在低版本浏览器中正常运行。
[接口数据]
- getMqttConnectInfo
返回值:
data: {
host: "mqtt.xxxx.net", // "mqtt域名",
port: 8084, // "mqtt端口",
secretKey: "mmmmmmm", //"mqtt密钥,mqtt密码 = md5(clientId,secretKey) ",
timestamp: 1758796, // "mqtt服务器时间戳",
token: "tokentokentoke token", //"clientid = token|sighmethod=md5,timestamp=nowdate ",
topic: "/message/yyyy", //"订阅主题",
username: "username", //"mqtt用户名",
},
[开始啦]
mqtt.js:
import { Message } from "element-ui";
// socket.readystate == 0 //正在建立连接
// == 1 //已经建立连接
// == 2 //正在关闭连接
// == 3 //已经关闭连接
class WEB_SOCKET {
websock = null;
messageCallback = null;
errorCallback = null;
wsUrl = "";
tryTime = 0;
// 初始化类实例
constructor(params) {
console.log("WEBSOCKET实例", params);
this.wsUrl = params.wsUrl;
this.messageCallback = params.messageCallback;
this.errorCallback = params.errorCallback;
}
/**
* 发起websocket连接
* @param {Object} agentData 需要向后台传递的参数数据
*/
websocketSend(agentData) {
console.log("发起websocket连接-----websocketSend");
// 加延迟是为了尽量让ws连接状态变为OPEN
setTimeout(() => {
console.log("发起连接", this.websock);
// 添加状态判断,当为OPEN时,发送消息
if (this.websock.readyState === this.websock.OPEN) {
// websock.OPEN = 1
// 发给后端的数据需要字符串化
this.websock.send(JSON.stringify(agentData));
}
if (this.websock.readyState === this.websock.CLOSED) {
// websock.CLOSED = 3
console.log("websock.readyState=3");
Message.error("ws连接异常,请稍候重试");
this.errorCallback();
}
}, 500);
}
// 关闭ws连接
websocketclose(e) {
console.log("关闭ws连接-----websocketclose", e);
// e.code === 1000 表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。
// e.code !== 1000 表示非正常关闭。
if (e && e.code !== 1000) {
Message.error("设备数据异常,请稍候重试");
this.errorCallback("正在关联");
// // 如果需要设置异常重连则可替换为下面的代码,自行进行测试
// if (tryTime < 10) {
// setTimeout(function() {
// websock = null
// tryTime++
// initWebSocket()
// console.log(`第${tryTime}次重连`)
// }, 3 * 1000)
//} else {
// Message.error('重连失败!请稍后重试')
//}
}
}
// 连接ws
connectSocket() {
if (typeof WebSocket === "undefined") {
Message.error("您的浏览器不支持WebSocket,无法获取数据");
return false;
}
console.log("重新请求", this.wsUrl, this.messageCallback);
this.websock = new WebSocket(this.wsUrl);
this.websock.onopen = () => {
// Message.success("ws连接成功");
this.messageCallback && this.messageCallback("open");
};
this.websock.onmessage = (e) => {
let mqData = JSON.parse(e.data);
// console.log('消息消息', e)
this.messageCallback && this.messageCallback(mqData);
};
this.websock.onerror = (e) => {
Message.error("设备数据异常,请稍候重试", e);
e.helen = "eror";
this.errorCallback && this.errorCallback(e);
};
this.websock.onclose = (e) => {
e.helen = "close";
// Message.error("ws主动关闭链接");
this.errorCallback && this.errorCallback(e);
};
}
/**
* 初始化websocket
* @param {string} url ws连接地址
* @param {function} successCallback 接收到ws数据,对数据进行处理的回调函数
* @param {function} errCallback ws连接错误的回调函数
*/
initWebSocket(url, successCallback, errCallback) {
this.wsUrl = url;
this.messageCallback = successCallback;
this.errorCallback = errCallback;
this.connectSocket();
}
// 关闭
closeWebsocket() {
if (this.websock) {
console.log("关闭websocket", this.websock, "close? onclose??");
this.websock.close(); // 关闭websocket
// this.websock.onclose(); // 关闭websocket
}
}
}
export default WEB_SOCKET;
使用:
import WEB_SOCKET from "@/utils/socket";
created() {
this.starSocket(securityKey);
},
destroyed() {
this.endSocket();
},
methods: {
// 连接webSocket
starSocket(key) {
console.log("连接webSocket前,变量:", this.PublicSocket);
// 防止用户多次连续点击发起请求,所以要先关闭上次的ws请求。
if (this.PublicSocket) {
this.endSocket();
}
const machineInfo = JSON.parse(localStorage.getItem("machineInfo"));
const host = window.location.host;
const url1 = `wss://${host}/djsupplier/websocket/channel/production`;
const deviceId = machineInfo ? machineInfo.deviceId : "";
//设置订阅地址
this.PublicSocket = new WEB_SOCKET({
wsUrl: url1 + "?deviceId=" + deviceId + "&yi_paper_sn=" + key,
messageCallback: this.wsMessage,
errorCallback: this.wsError,
});
// 发起ws请求
this.PublicSocket.connectSocket();
},
// 结束连接mqtt
endSocket() {
if (this.PublicSocket) {
this.PublicSocket.closeWebsocket();
this.PublicSocket = null;
}
},
wsMessage(data) {
this.$refs.machineStateRef.wsMessage(data);
},
// ws连接失败,组件要执行的代码
wsError(error) {
this.$refs.machineStateRef.wsError(error);
},
}