vue 使用websocket
data(){
return {
lockReconnect: false,//是否真正建立连接
timeout: 5*1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
}
}
// websocket 连接
initWebSocket() {
//初始化websocket
const wsuri = "wss://10.0.0.113/460/measureDetect/WebSocket"; // 后台给的地址
this.websock = new WebSocket(wsuri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
// 打开
websocketonopen(e) { //连接建立之后执行send方法发送数据
console.log(this.websock);
this.$Message.success('已监听');
console.log(e);
console.log("Socket 已打开");
//开启心跳
this.start();
},
// error
websocketonerror(e) {//连接建立失败重连
console.log(e);
console.log('socket出错')
//重连
this.reconnect();
},
// 返回信息 //接受信息,后台返回的数据
websocketonmessage(e) {
console.log(e);
if (e.data){
if (e.data == 'pong'){
this.reset();
} else {
this.data = e.data;
console.log('接收数据' + ' ... ' + e.data);
//收到服务器信息,心跳重置
this.reset();
}
}
},
// 发送信息 // 把你需要传给后台的信息传过去
websocketsend(data) {//数据发送
this.websock.send(data);
console.log('发送测试');
},
// 关闭
websocketclose(e) {
console.log('断开连接', e);
//重连
this.reconnect();
},
// 心跳 //重新连接
reconnect() {
var that = this;
if(that.lockReconnect) {
return;
}
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function () {
//新连接
that.initWebSocket();
that.lockReconnect = false;
},500);
},
//重置心跳
reset(){
var that = this;
//清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
//重启心跳
that.start();
},
//开启心跳
start(){
var self = this;
self.timeoutObj && clearTimeout(self.timeoutObj);
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
self.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (self.websock.readyState == 1) {//如果连接正常
self.websock.send("ping");
}else{//否则重连
self.reconnect();
}
//定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
self.serverTimeoutObj = setTimeout(function() {
console.log('超时')
//超时关闭
self.websock.close();
}, self.timeout);
}, self.timeout)
},