vue+websocket demo:
<-! Vue + websocket connection Demo ->
<Template>
<div class = ""> + WebSocket connection VUE Demo </ div>
</ Template>
<Script>
Export default {
Data () {
return {
// connector flag
lockReconnect: to false ,
wsCfg: {
// WebSocket address
URL: 'WS: //10.74.52.107: 9001 / WebSocket'
}
};
},
Methods: {
createWebSocket () {
the try {
// create Web Socket connector
const socket = new newA WebSocket ( the this .wsCfg.url);
// initialize event
the this .initEventHandle (Socket);
} the catch (E) {
// reconnect Error
the this .reconnect ( the this .wsCfg.url);
}
},
initEventHandle (Socket) {
// trigger when the connection is closed
socket.onclose = () => {
the console.log ( 'closed connection " );
};
// triggered when a communication error occurs
socket.onerror = () => {
// recreated long link
this.reconnect ();
};
// trigger connection establishment
socket.onopen = () => {
the console.log ( 'connection success' );
};
// triggered when the client receives the server data
socket.onmessage = msg = > {
// service logic processing
the this .list = msg.data;
};
},
reconnect () {
IF ( the this .lockReconnect) {
return ;
}
the this .lockReconnect = to true ;
// will always reconnect the connector is not provided avoid excessive delay request
setTimeout(() => {
this.lockReconnect = false;
this.createWebSocket(this.wsCfg.url);
}, 2000);
}
},
mounted() {
this.createWebSocket();
}
};
</script>