1、優(yōu)化
參考了網(wǎng)上幾篇文章,對其中代碼做了優(yōu)化,加了重連機(jī)制和心跳檢測,添加相應(yīng)注釋。
我剛嘗試的時候因?yàn)闆]有websocket服務(wù)端,無意中發(fā)現(xiàn)一個免費(fèi)的服務(wù)端。一個帥哥服務(wù)端
如果你想自己玩玩WebSocket, 但是你又不想自己部署一個WebSocket服務(wù)器,你可以使用ws = new WebSocket('wss://echo.websocket.org/'), 你向echo.websocket.org發(fā)送消息,它會回復(fù)你同樣的消息。
2、代碼(在vue當(dāng)中)
WebSocket到現(xiàn)在成功運(yùn)行一個月,前端沒出任何問題(2019-04-04更新)
data(){
return{
websock: null,
reconnectData:null,
lockReconnect:false, //避免重復(fù)連接,因?yàn)閛nerror之后會立即觸發(fā) onclose
timeout:10000, //10s一次心跳檢測
timeoutObj:null,
serverTimeoutObj:null,
}
},
created(){
this.initWebSocket();
},
methods:{
initWebSocket(){
console.log('啟動中')
let wsurl = '你的websockt url';
this.websock = new WebSocket(wsurl);
this.websock.onopen = this.websocketonopen; //連接成功
this.websock.onmessage = this.websocketonmessage; //廣播成功
this.websock.onerror = this.websocketonerror; //連接斷開,失敗
this.websock.onclose = this.websocketclose; //連接關(guān)閉
}, //初始化weosocket
websocketonopen(){
console.log('連接成功')
this.heatBeat();
}, //連接成功
websocketonerror(){
console.log('連接失敗')
this.reconnect();
}, //連接失敗
websocketclose(){
console.log('斷開連接');
this.reconnect();
}, //各種問題導(dǎo)致的 連接關(guān)閉
websocketonmessage(data){
this.heatBeat(); //收到消息會刷新心跳檢測,如果一直收到消息,就推遲心跳發(fā)送
let msgData = JSON.parse(data);
}, //數(shù)據(jù)接收
websocketsend(data){
this.websock.send(JSON.stringify(data));
}, //數(shù)據(jù)發(fā)送
reconnect(){
if(this.lockReconnect){ //這里很關(guān)鍵,因?yàn)檫B接失敗之后之后會相繼觸發(fā) 連接關(guān)閉,不然會連接上兩個 WebSocket
return
}
this.lockReconnect = true;
this.reconnectData && clearTimeout(this.reconnectData);
this.reconnectData = setTimeout(()=>{
this.initWebSocket();
this.lockReconnect = false;
},5000)
}, //socket重連
heatBeat(){
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(()=>{
this.websocketsend({type:'心跳檢測'}) //根據(jù)后臺要求發(fā)送
this.serverTimeoutObj = setTimeout(()=> {
this.websock.close(); //如果 5秒之后我們沒有收到 后臺返回的心跳檢測數(shù)據(jù) 斷開socket,斷開后會啟動重連機(jī)制
}, 5000);
}, this.timeout)
}, //心跳檢測
},
destroyed() {
this.lockReconnect = true;
this.websock.close() //離開路由之后斷開websocket連接
clearTimeout(this.reconnectData); //離開清除 timeout
clearTimeout(this.timeoutObj); //離開清除 timeout
clearTimeout(this.serverTimeoutObj); //離開清除 timeout
}