Optimize performance using websocket connection
need
Front-end echarts chart display, refresh the data every five seconds
question
In the early stage, we used axios polling, adding a timer to request the interface once a second, which caused a stuttering and a huge burden on the server. Different people may display different data when they are opened.
solve
Use websocket to create long connection
(Websocket only requires an HTTP handshake, so the entire communication process is established in a connection/state, which avoids the non-state nature of HTTP. The server will always know your information until you close the request)
data(){ WsUrl:'',//Website lock:false//Repeat link identification url:'', token:'', deviceid:'', reconnetTimeout:null, timer:null, serverTimer:null, timeout:10*1000 } mounted () { () }, methods:{ createWebsocket(){ try{ initWebSocket() }catch{ reConnect() } } initWebSocket () { // Create a constructor to return a websocket object = `ws://${}${}${}?deviceid=${}` = new WebSocket(wsurl) // Callback function after receiving the information = // Callback function after successful connection = // Callback function after connection failure = // Used to specify a closed callback function = }, // Connection establishment failed and reconnected websocketonerror () { () }, websocketonopen(){ () () } // Data Receive websocketonmessage (e) { // Handle business logic if(==‘pong'){ () } } // closure websocketclose (e) { () }, } reConnect() { if() { return; }; = true; //If there is no connection, it will be reconnected all the time. Set delay to avoid too many requests && clearTimeout(); = setTimeout(function () { (); = false; }, 4000); } WebsocketSend(){ (‘ping') } start(ws){ &&clearTimeout() &&clearTimeout() =setTimeout(()=>{ (‘ping') =setTimeout(()=>{ () },}; },) }
Use of websocket on vue
<template> <div> <button @click="send">Send a message</button> </div> </template> <script> export default { data () { return { path:"ws://192.168.1.145:8080", socket:"" } }, mounted () { // Initialization () }, methods: { init: function () { if(typeof(WebSocket) === "undefined"){ alert("Your browser does not support socket") }else{ // Instantiate the socket = new WebSocket() // Listen to socket connections = // Listen to socket error message = // Listen to socket messages = } }, open: function (res) { ("Socket connection is successful") }, error: function () { ("Connection Error") }, getMessage: function (msg) { /*data*/ () }, /* send: function () { (params) },*/ close: function () { ("Socket has been closed") } }, destroyed () { // Destroy the monitor = } } </script> <style> </style>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.