Home Web Front-end Vue.js How to use WebSocket to achieve real-time communication in Vue

How to use WebSocket to achieve real-time communication in Vue

Jun 11, 2023 am 11:46 AM
vue websocket real time communication

Vue is a popular JavaScript framework for building dynamic user interfaces and Single-Page Applications. WebSocket is a network tool based on the TCP protocol for real-time communication. Combining WebSocket in Vue can achieve real-time data transmission and promote real-time communication between front-end applications and back-end. This article will introduce how to use Vue and WebSocket to achieve real-time communication.

1. Basic knowledge of WebSocket

  1. Characteristics of WebSocket

WebSocket is a full-duplex, long-connection protocol with the following characteristics:

  • Two-way communication: Both the client and the server can send information.
  • Real-time communication: No need to regularly request the server, the server can actively push information to the client.
  • Lower delay: WebSocket has smaller data transmission delay and higher data transmission efficiency.
  • Scalability: The HTTP protocol used by WebSocket is the handshake protocol and follows the RESTful specification.
  1. Usage scenarios of WebSocket

WebSocket is mainly used in scenarios where the server pushes real-time information to the client, such as chat rooms, online games, real-time stock quotes, etc. .

  1. WebSocket implementation

WebSocket achieves two-way communication by establishing a TCP connection between the server and the client. The communication process is as follows:

First , the client sends a request to the server. The request header contains the Upgrade and Connection fields, telling the server to upgrade the protocol and use WebSocket to connect. After receiving the request, the server returns a response message. The response contains status code 101 Switching Protocols and an Upgrade header field, indicating that the connection has been successfully established. After the two parties are successfully connected, they can send information to each other, and when either party terminates the connection, the TCP connection is interrupted.

2. Using WebSocket in Vue

  1. Installing the WebSocket library

Using WebSocket in Vue requires installing the corresponding library. We can use the vue-native-websocket plug-in, which is a WebSocket plug-in for Vue.js. The installation method is as follows:

npm install vue-native-websocket --save
Copy after login

Among them, the --save option means to save the plug-in as a dependency in the package.json file.

  1. Using the WebSocket plug-in

After the installation is complete, we need to enable WebSocket in the Vue instance. In Vue's main.js file, we can configure it like this:

import VueNativeSock from 'vue-native-websocket'

Vue.use(VueNativeSock, 'ws://localhost:3000', {
  store: store, //将store注入到VueNativeSock实例中,使其能够访问store中的state和action。
  format: 'json', //设置数据格式为JSON
  reconnection: true, //断开连接时自动重新连接
  reconnectionAttempts: 5, //重新连接的最大尝试次数
  reconnectionDelay: 3000, //重新连接的时间间隔
})
Copy after login

The above code uses the WebSocket plug-in as a plug-in for Vue. Among them, the first parameter is the URL of the WebSocket connection, and the second parameter is a configuration object. We have set some options, such as formatting data in JSON format, enabling automatic reconnection, etc.

Next, we can define a WebSocket instance in the Vue component to implement real-time communication functionality. For example, we can define a Vue component named WebSocketExample like this:

<template>
  <div>
    <h1>WebSocketExample</h1>
    <div>
      <input type="text" v-model="message" placeholder="input message" />
      <button @click="send">Send</button>
    </div>
    <ul>
      <li v-for="msg in messages" :key="msg.id">{{msg.text}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'WebSocketExample',
  data() {
    return {
      message: '',
      messages: [],
    }
  },
  methods: {
    send() {
      this.$socket.send(
        JSON.stringify({
          message: this.message,
        })
      )
      //清空输入框
      this.message = ''
    },
  },
  mounted() {
    this.$socket.onMessage((msg) => {
      console.log('Received:', msg.data)
      const message = JSON.parse(msg.data)
      this.messages.push({
        id: Math.random()
          .toString()
          .slice(2),
        text: message.message,
      })
    })
  },
}
</script>
Copy after login

In the above code, we define a Vue component containing a text box and a list, enter information through the text box and send it, and then Display information in a list. We use the mounted() function to start listening to WebSocket message events after the component is loaded, save the received messages in the messages array, and then traverse and display them on the page.

After we configure the store in the main.js file, we can use the store's methods and status data in the VueNativeSock instance. For example, you can use this.$store.dispatch() method in methods to send actions, and you can use this.$store.state to access state data in mounted().

3. Summary

The combination of Vue and WebSocket can easily achieve real-time communication between the front end and the back end. We use the vue-native-websocket plug-in in Vue to implement WebSocket connection, and implement a simple chat room example. Through the combination of Vue and WebSocket, we can quickly build real-time applications and realize real-time transmission of data.

The above is the detailed content of How to use WebSocket to achieve real-time communication in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles