<template>
<div></div>
</template>
<script>
export default{
data(){
return{
socketUrl:"",
socket:null,
pingTimer:null
}
},
mounted(){
this.init_websocket();
},
methods:{
init_websocket(){
try{
if('WebSocket' in window){
this.socket = new Websocket(this.socketUrl);
}else{
console.log('您的浏览器不支持websocket');
}
this.socket.onopen = this.websocketonopen;
this.socket.onerror = this.websocketonerror;
this.socket.onmessage = this.websocketonmessage;
this.socket.onclose = this.websocketonclose;
}catch(e){
this.reconnect();
}
},
reconnect(){
console.log('尝试重连');
setTimeout(()=>{
this.init_websocket();
},1 * 1000);
},
websocketonopen(){
this.login_websocket();
},
websocketonerror(e){
clearInterval(this.pingTimer);
console.log('error',e);
this.reconnect();
},
websocketonmessage(e){
let data = JSON.parse(e.data);
console.log('得到响应',data);
},
websocketonclose(){
clearInterval(this.pingTimer);
this.reconnect();
},
send_ping(){
this.pingTimer = setInterval(()=>{
this.socket.send(
JSON.stringfy({
type:'ping'
})
);
},50 * 1000);
},
login_websocket(){
let login_data = {...};
this.socket.send(JSON.stringfy(login_data));
this.send_ping();
},
},
destroyed(){
clearInterval(this.pingTimer);
this.socket.close();
}
}
</script>