data(){
return {
// path: "ws://192.168.1.85:8007/fmis-api/dispatch/1",
path: window.WS + "/dispatch/1",
// path:process.env.VUE_APP_WEBBASE_API+"/dispatch/1",
socket: "",
lockReconnect: false,//是否真正建立连接
timeout: 28*1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
}
},
mounted{
// 初始化———websocket
this.initWesocket();
},
methods:{
initWesocket() {
if (typeof WebSocket === "undefined") {
alert("您的浏览器不支持socket");
} else {
// 实例化socket
this.socket = new WebSocket(this.path);
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket错误信息
this.socket.onerror = this.error;
this.socket.onclose = this.onclose;
// 监听socket消息
this.socket.onmessage = this.getMessage;
}
},
onclose(e) {
console.log("连接关闭");
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
//重连
this.reconnect();
},
reconnect() {//重新连接
if(this.lockReconnect) {
return;
};
this.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
this.timeoutnum && clearTimeout(this.timeoutnum);
this.timeoutnum = setTimeout( ()=>{
//新连接
this.init();
this.lockReconnect = false;
},5000);
},
reset(){//重置心跳
//清除时间
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
//重启心跳
this.start();
},
start(){//开启心跳
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(()=>{
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (this.socket.readyState == 1) {//如果连接正常
this.socket.send("heartCheck");
}else{//否则重连
this.reconnect();
}
this.serverTimeoutObj = setTimeout(()=> {
//超时关闭
this.socket.close();
}, this.timeout);
}, this.timeout)
},
open() {
console.log("socket连接成功");
//开启心跳
this.start();
},
error() {
console.log("连接错误");
//重连
this.reconnect();
},
getMessage(msg) {
console.log(msg.data, "有消息!!!");
//处理具体业务
// var arr = JSON.parse(msg.data);
// console.log(typeof arr,"类型");
if(this.userName=='0003'){
//收到服务器信息,心跳重置
this.reset();
if (msg.data.includes("error:")) {
return this.$message.error(msg.data.replace("error:", ""));
} else {
let arr = [];
let s1 = msg.data.split(",");
s1.forEach((item, i) => {
// console.log(item);
let obj = {};
obj.id = item;
arr.push(obj);
});
console.log(arr, "数组形式");
if (arr != null && arr.length > 0) {
this.onSubmit("search");
this.carList = arr;
console.log(typeof this.carList, "类型");
console.log(this.carList);
this.carList.forEach((item) => {
console.log(item, "批量打印派车单ID");
this.PrintDispatchList(item.id);
});
}
}
}
},
send() {
this.socket.send("主动发送消息");
},
}
vue websoket 心跳机制使用笔记
最新推荐文章于 2025-03-25 21:58:09 发布