data () {
return {
ws: null,//建立的連接
lockReconnect: false,//是否真正建立連接
timeout: 28*1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒計時
serverTimeoutObj: null,//心跳倒計時
timeoutnum: null,//斷開 重連倒計時
}
},
created() {
this.initWebpack();
},
methods: {
initWebpack(){
this.ws = new WebSocket(process.env.SOCKET_OTC);
this.ws.onopen = this.onopen;
this.ws.onmessage = this.onmessage;
this.ws.onclose = this.onclose;
this.ws.onerror = this.onerror;
},
reconnect() {//重新連接
var that = this;
if(that.lockReconnect) {
return;
};
that.lockReconnect = true;
//沒連接上會一直重連,設置延遲避免請求過多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function () {
//新連接
that.initWebpack();
that.lockReconnect = false;
},5000);
},
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.ws.readyState == 1) {//如果連接正常
self.ws.send("heartCheck");
}else{//否則重連
self.reconnect();
}
self.serverTimeoutObj = setTimeout(function() {
//超時關閉
self.ws.close();
}, self.timeout);
}, self.timeout)
},
onopen() {
var msg = JSON.stringify({cmd: 'enter_chatting', token:this.COOKIE.getCookie("token")});
this.ws.send(msg);
console.log("open");
this.getNoReadRecords();
//開啟心跳
this.start();
},
onmessage(e) {
this.mydata = JSON.parse(e.data);
if(this.mydata.fromID == this.states.customerId){
this.mydata.chatType = 2;
}else{
this.mydata.chatType = 1;
}
var content =this.getContentTypes(this.mydata.content,this.mydata.chatType);
this.records.push(this.mydata);
//收到服務器信息,心跳重置
this.reset();
},
onclose(e) {
console.log("連接關閉");
console.log('websocket 斷開: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
var msg = JSON.stringify({cmd: 'out_chatting', token:this.COOKIE.getCookie("token")});
this.ws.send(msg);
//重連
this.reconnect();
},
onerror(e) {
console.log("出現錯誤");
//重連
this.reconnect();
}
}