vue + websocket

// ----------------- websocket(开始) ----------------
// 初始化
initWebSocket() {

const wsurl = webSocketUrl;

this.websock = new WebSocket(wsurl);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
// 连接成功
websocketonopen() {
console.log("WebSocket连接成功");
const params = {
FG: "REG",
planId: this.$route.params.id
};
this.websocketsend(JSON.stringify(params));
let data = {
time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
log: "WebSocket连接成功,等待返回数据",
state: "0"
};
this.updataLog.push(data);
},
// 连接发成错误
websocketonerror(e) {
this.$Message.warning("WebSocket连接发生错误");
let data = {
time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
log: "WebSocket连接发生错误,本次未获取到日志记录",
state: "1"
};
this.updataLog.unshift(data);
// console.log('WebSocket连接发生错误');
},
//数据接收
websocketonmessage(e) {
let redata = JSON.parse(e.data);
if (this.getSelectOne.deviceName === redata.neName) {
if (redata.log !== "EOF") {
this.dataAll += redata.log;
return;
}
let newLogs = JSON.parse(this.dataAll);
let num = newLogs.length - this.logArr.length;
this.$Message.success({
content: "本次新增了" + num + "条日志信息",
duration: 3
});
this.logArr = newLogs;
this.riskNum = 0;
console.log("11111111", this.logArr);
this.dataAll = "";
this.logArr.forEach(item => {
if (item.isDanger === "Y") {
this.riskNum += 1;
}
});
let data = {
time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
log: `请求成功,本次新增了${num}条日志信息`,
state: "0"
};
this.updataLog.unshift(data);
}
},
//数据发送
websocketsend(agentData) {
console.log("22222", agentData);
this.websock.send(agentData);
},
//关闭
websocketclose(e) {
console.log("connection closed (" + "e.code" + ")");
}
},
destroyed() {
//页面销毁时关闭长连接
this.websocketclose();
},
// -------------------- end -------------------------

猜你喜欢

转载自www.cnblogs.com/yanxiase/p/10097300.html