Vue.js WebSocket Integration Guide: The perfect solution for real-time communication

Introduction

WebSocket is a communication protocol that enables two-way communication in web applications. It allows a persistent, low-latency connection between a client and a server for real-time data transfer. Compared with traditional HTTP requests, WebSocket is more suitable for applications that require real-time and interactivity.

Why do you need WebSocket?

WebSocket solves some limitations of traditional HTTP requests, such as:

  • Real-time: Traditional HTTP requests require the client to periodically poll the server for new data, while WebSocket allows the server to actively push data to the client to achieve real-time updates.
  • Two-way communication: WebSocket supports two-way communication. Both the client and the server can send messages, instead of being limited to the client sending requests to the server.
  • Low latency: WebSocket connections remain open, reducing the overhead of connecting and disconnecting, resulting in lower communication latency.

WebSocket connection in Vue.js

Vue.js is a popular JavaScript framework that makes building modern web applications easier. Implementing WebSocket connections in Vue.js makes it easy to integrate real-time communication capabilities into applications.

Websocket common events

  • setupWebSocket(): Used to create a WebSocket connection, configure the WebSocket object, and define the event handling function of the connection.
  • closeWebSocket(): used to close the WebSocket connection.
  • onWebSocketOpen(): event handling function when WebSocket connection is successful.
  • onWebSocketMessage(event): Process the received WebSocket message.
  • onWebSocketClose(): Handles the WebSocket connection closing event.
  • sendMessage(message): used to send messages to the WebSocket server.
  • startHeartbeat(): Start heartbeat detection.
  • stopHeartbeat(): Stop heartbeat detection.

WebSocket connection configuration

First, we need to create a Vue.js component that is responsible for the creation and management of WebSocket connections. In the data attribute of the component, we define the WebSocket object

<template>
  <div>
   
  </div>
</template>

<script>
export default {<!-- -->
  data() {<!-- -->
    return {<!-- -->
      websocket: null, // WebSocket object
    };
  },
  created() {<!-- -->
    this.setupWebSocket(); // Create WebSocket connection
  },
  beforeDestroy() {<!-- -->
    this.closeWebSocket(); // Close the WebSocket connection before the component is destroyed
  },
  methods: {<!-- -->
     setupWebSocket() {<!-- -->
      this.websocket = new WebSocket("ws link"); // Create a WebSocket connection
      this.websocket.onopen = this.onWebSocketOpen; //Handling function when WebSocket connection is opened
      this.websocket.onmessage = this.onWebSocketMessage; //Handling function when receiving WebSocket message
      this.websocket.onclose = this.onWebSocketClose; //Handling function when the WebSocket connection is closed
    },
    onWebSocketOpen() {<!-- -->
      console.log("Link successful");
    },
    closeWebSocket() {<!-- -->
      if (this.websocket) {<!-- -->
        this.websocket.close(); // Close the WebSocket connection
      }
    },
  },
};
</script>

Send initialization message

After the WebSocket connection is successful, we can send an initialization message to the server in the onWebSocketOpen method. The content and format of the initialization message should be defined according to the server’s requirements.

methods: {<!-- -->
  onWebSocketOpen() {<!-- -->
   console.log("Link successful");
    \t
    //Send initialization message according to backend definition
    const initMessage = {<!-- -->
      type: 'sub',
      topic: '/aa/bb/cc/d',
      parameter: {<!-- -->},
      id: 'bb',
    };
    this.sendMessage(JSON.stringify(initMessage));
},
sendMessage(message) {<!-- -->
      if (this.websocket & amp; & amp; this.websocket.readyState === WebSocket.OPEN) {<!-- -->
        this.websocket.send(message); //Send message to WebSocket server
      }
    },

  // Other methods
}

In this way, when the WebSocket connection is successful, an initialization message will be automatically sent to the server in order to initiate two-way communication.

Receive WebSocket messages

In the onWebSocketMessage method, we obtain the message received from the server through event.data, and then perform corresponding operations based on the content of the message.

methods: {<!-- -->
  // ... Other methods ...

  onWebSocketMessage(event) {<!-- -->
    const message = event.data;
    // Handle messages received from the server
    console.log('Received message:', message);

    // Here you can perform different operations based on the content of the message, such as updating the interface, triggering events, etc.
  },

  // ... Other methods ...
}

Set reconnection interval and heartbeat

export default {<!-- -->
  data() {<!-- -->
    return {<!-- -->
      websocket: null, // WebSocket object
      reconnectInterval: 3000, // Reconnection interval (milliseconds)
    };
  },
  methods: {<!-- -->
     // ... Other methods ...
onWebSocketOpen() {<!-- -->
   console.log("Link successful");
    this.startHeartbeat(); // Start heartbeat
    //Send initialization message according to backend definition
    const initMessage = {<!-- -->
      type: 'sub',
      topic: '/aa/bb/cc/d',
      parameter: {<!-- -->},
      id: 'bb',
    };
    this.sendMessage(JSON.stringify(initMessage));
},
  startHeartbeat() {<!-- -->
      this.heartbeatInterval = setInterval(() => {<!-- -->
        if (this.websocket & amp; & amp; this.websocket.readyState === WebSocket.OPEN) {<!-- -->
          this.websocket.send("ping"); // Send heartbeat message
        }
      }, 10000); // Send a heartbeat every 10 seconds
    },
    stopHeartbeat() {<!-- -->
      if (this.heartbeatInterval) {<!-- -->
        clearInterval(this.heartbeatInterval); // Stop the heartbeat detection timer
      }
    },
onWebSocketClose() {<!-- -->
      console.log("WebSocket connection is closed");
  this.stopHeartbeat(); // Stop heartbeat detection when the WebSocket connection is closed
      setTimeout(this.setupWebSocket, this.reconnectInterval); //Reconnect to WebSocket after a certain period of time
     },
       // ... Other methods ...
  },
};
}

Heartbeat detection timer

export default {<!-- -->
  data() {<!-- -->
    return {<!-- -->
      websocket: null, // WebSocket object
      reconnectInterval: 3000, // Reconnection interval (milliseconds)
      heartbeatInterval: null, // Heartbeat timer
    };
  },
  methods: {<!-- -->
     // ... Other methods ...
    
onWebSocketClose() {<!-- -->
      console.log("WebSocket connection is closed");
      setTimeout(this.setupWebSocket, this.reconnectInterval); //Reconnect to WebSocket after a certain period of time
     },
       // ... Other methods ...
  },
};
}

Complete code

<template>
  <div></div>
</template>

<script>
export default {<!-- -->
  data() {<!-- -->
    return {<!-- -->
      websocket: null, // WebSocket object
      reconnectInterval: 3000, // Reconnection interval (milliseconds)
      heartbeatInterval: null, //Heartbeat timer
    };
  },
  created() {<!-- -->
    this.setupWebSocket(); // Create WebSocket connection
  },
  methods: {<!-- -->
    setupWebSocket() {<!-- -->
      this.websocket = new WebSocket("ws link address"); // Create a WebSocket connection
      this.websocket.onopen = this.onWebSocketOpen; //Handling function when WebSocket connection is opened
      this.websocket.onmessage = this.onWebSocketMessage; //Handling function when receiving WebSocket message
      this.websocket.onclose = this.onWebSocketClose; //Handling function when the WebSocket connection is closed
    },
    closeWebSocket() {<!-- -->
      if (this.websocket) {<!-- -->
        this.websocket.close(); // Close the WebSocket connection
      }
    },
    /**
     * After the WebSocket connection is opened, start heartbeat detection
     */
    onWebSocketOpen() {<!-- -->
      console.log("WebSocket connection is open");
      this.startHeartbeat();
      //Send initialization message
      const initMessage = {<!-- -->
        type: "sub",
        topic: "/aa/bb/cc/d",
        parameter: {<!-- -->},
        id: "bb",
      };
      this.sendMessage(JSON.stringify(initMessage));
    },
    // Handle messages received from the server
    onWebSocketMessage(event) {<!-- -->
      if (event.data) {<!-- -->
        const message = JSON.parse(event.data);
        //Process data according to business
      }
    },
    onWebSocketClose() {<!-- -->
      console.log("WebSocket connection is closed");
      this.stopHeartbeat(); // Stop heartbeat detection when the WebSocket connection is closed
      setTimeout(this.setupWebSocket, this.reconnectInterval); //Reconnect to WebSocket after a certain period of time
    },
    sendMessage(message) {<!-- -->
      if (this.websocket & amp; & amp; this.websocket.readyState === WebSocket.OPEN) {<!-- -->
        this.websocket.send(message); //Send message to WebSocket server
      }
    },
    startHeartbeat() {<!-- -->
      this.heartbeatInterval = setInterval(() => {<!-- -->
        if (this.websocket & amp; & amp; this.websocket.readyState === WebSocket.OPEN) {<!-- -->
          this.websocket.send("ping"); // Send heartbeat message
        }
      }, 10000); // Send a heartbeat every 10 seconds
    },
    stopHeartbeat() {<!-- -->
      if (this.heartbeatInterval) {<!-- -->
        clearInterval(this.heartbeatInterval); // Stop the heartbeat detection timer
      }
    },
  },
  beforeDestroy() {<!-- -->
    this.closeWebSocket(); // Close the WebSocket connection before the component is destroyed
  },
};
</script>
<style lang="scss" scoped></style>

Summary

In the article, we learned how to integrate WebSocket in Vue.js application for real-time communication. It brings many possibilities to your application. Here are some key takeaways:

  1. Create WebSocket connection: We created a Vue.js component to manage WebSocket connections. This component initializes the WebSocket object and defines the event handling function of the connection to ensure that the connection can operate normally.
  2. Message processing: We implemented functions for processing WebSocket messages. When the server sends messages, we are able to capture these messages and execute the corresponding logic.
  3. Heartbeat detection: By implementing heartbeat detection, we can keep the WebSocket connection active and prevent the connection from being disconnected. This is a key feature in real-time communication applications.
  4. Disconnection and reconnection: When the connection is closed unexpectedly, we ensure that the application can continue to stay connected through automatic reconnection, providing a seamless user experience.

Finally, WebSocket functionality can be easily integrated, allowing applications to excel in real-time communication. This feature has wide application for a variety of applications, including chat applications, collaboration tools, and monitoring systems.