Vue uses websocket to implement real-time data push and publish, subscribe and reconnect single sign-on functions.

Requirements: Use websocket to implement publishing, subscribing, network disconnection and reconnection, and account squeezing after single sign-in without using plug-ins.

1. Single sign-on (only one of the same account is online at the same time, multiple user logins are prohibited)

Implementation: After the user logs in, the token token is obtained and stored locally. It can be judged whether the token token has expired to allow the user to log out. The operation of websocket is to allow the user to connect to the websocket after logging in and send instructions. The instructions sent here It is given by the backend, and then the frontend receives the message. If the message is for logging out, just ask him to clear the local area and jump to the login page.

1. Log in to obtain the token and store it in localStorage

2. Get the token in the layout, which is the main frame of the page, and connect to the websocket

3. After the connection is successful, send the command directly, and then monitor the message returned to the front end to implement the exit operation.

url = `${protocol}://websocket address, the backend needs to give ?token=${token}`;,

Let me give you an example. The connection address should be like this: ws://127.0.0.1:8080?token=362466325,

ws.send(`msg:${this.data.id}`); This is also decided by the backend to give him the account id, so as to monitor the login.

Reconnect, then the message returns to loginOut and then log out. If the link is closed for various reasons, directly request reconnection.

retryCount: 0,

maxRetryCount: 5,

retryInterval: 2000, //Retry interval, unit: milliseconds

Notice! ! It seems that websocket cannot set the request header to carry token. I have tried many times but it doesn’t work. Even using the ws plug-in doesn’t work. I can only splice the token to the backend. If there is a better way, you can contact me in the comment area.

let ws;
let url = "";
export default {
 mounted() {
    this.connectWebsocket();
  },
  methods: {
    connectWebsocket() {
      let protocol = "ws";

      if (typeof WebSocket === "undefined") {
        console.log("Your browser does not support WebSocket");
        return;
      } else {
        if (window.location.protocol == "https:") {
          protocol = "wss";
        }
        let token = localStorage.getItem("token");
        url = `${protocol}://websocket address, the backend needs to give ?token=${token}`;
        //Open a ws
        ws = new WebSocket(url);
        ws.onopen = () => {
          // send data
          console.log("ws is connected!!");
          ws.send(`msg:${this.data.id}`);
          // this.$message.success("ws is connected!!");
        };
        //When an error occurs
        ws.onerror = (evt) => {
          console.log("ws error:", evt);
        };
        // close connection
        ws.onclose = (event) => {
          console.warn("WebSocket is closed");
          console.log("Close code:", event.code);
          console.log("Close reason:", event.reason);
          // Handle connection disconnection event
          this.handleWebSocketClose();
        };
        ws.onmessage = (evt) => {
          if (evt.data == "loginOut") {
            // At this time, we need to clear the data
            this.$message.warning("Your account was logged in at another location and you have been forced offline!!");
            this.$router.replace("/");
            localStorage.clear();
            ws.close();
            ws.onclose = () => {
              console.log("ws disconnected successfully");
            };
          }
          console.log(evt, "Message received");
        };
        this.$bus.$emit("Websocket", ws);
      }
    },
    handleWebSocketClose() {
      if (this.retryCount <this.maxRetryCount) {
        console.log(`Attempting to reconnect for the ${this.retryCount + 1} time...`);
        setTimeout(() => {
          this.connectWebsocket();
          this.retryCount + + ;
        }, this.retryInterval);
      } else {
        console.error("WebSocket connection failed, the maximum number of retries has been reached");
      }
    },
}
}

2. Publish and subscribe

Notice! ! A new message should be reconnected here every time it is published, otherwise it will be confused with the previous login message, especially when doing operations, such as el-table editing operations, every time To close the pop-up window, you must close the websocket. If it is confused with the login message, you will not be able to receive the message from the single sign-in in real time if you close the pop-up window.

This connectWebsocket is not the same as the one above. This is a websocket connection that needs to push the page in real time and will not affect the global single sign-on.

<script>
let websocket;
let url = "";
    export default {
connectWebsocket(data) {
      let protocol = "ws";

      if (typeof WebSocket === "undefined") {
        console.log("Your browser does not support WebSocket");
        return;
      } else {
        if (window.location.protocol == "https:") {
          protocol = "wss";
        }
        let token = localStorage.getItem("token");
        url = `${protocol}://The address given by the backend?token=${token}`;
        //Open a websocket
        websocket = new WebSocket(url);
        websocket.onopen = () => {
          // send data
          // console.log("websocket is connected!!");
          websocket.send(data);
          this.$message.success("websocket is connected!!");
        };
        //When an error occurs
        websocket.onerror = (evt) => {
          console.log("websocket error:", evt);
        };
        // close connection
        websocket.onclose = (event) => {
          console.warn("WebSocket is closed");
          console.log("Close code:", event.code);
          console.log("Close reason:", event.reason);
          // Handle connection disconnection event
          this.handleWebSocketClose(data);
        };
      }
    },
    handleWebSocketClose(data) {
      if (this.retryCount <this.maxRetryCount) {
        console.log(`Attempting to reconnect for ${this.retryCount + 1} times...`);
        setTimeout(() => {
          this.connectWebsocket(data);
          this.retryCount + + ;
        }, this.retryInterval);
      } else {
        this.$message.error("WebSocket connection failed!!");
        console.error("WebSocket connection failed, the maximum number of retries has been reached");
      }
    },
}
</script>

2.1 Simulating editing operations requires publishing messages

1. Click edit to open and receive in real time

 updData(row) {
      this.connectWebsocket(`data_imei:${row.id}`);
      websocket.onmessage = (evt) => {
    //If the received message is msgUpd
    if(evt.data=='msgUpd'){
  let data = JSON.parse(evt.data);
    //Just convert the obtained data to json and then display it to tableData.
    let tableData.unshift(data)
    //You can't accept it all the time. How much data is there? Define how many pieces are received and then intercept them.
      if (tableData.length > 500) {
           tableData.splice(500);
          }
        }
    }
}

2. You need to disconnect after closing the pop-up window

 closeWebSocket() {
      if (websocket != null) {
        websocket.close();
        websocket.onclose = () => {
          console.log("websocket disconnected successfully");
        };
      }
    },

3. Close the connection after leaving the websocket push page

 destroyed() {
    if (websocket != null) {
      websocket.close();
      websocket.onclose = () => {
        console.log("websocket disconnected successfully");
      };
    }
  },

The article ends here, I hope it helps you~~

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Network Skill TreeHomepageOverview 42424 people are learning the system