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

WBOY
WBOYOriginal
2023-06-11 11:46:414618browse

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

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, //重新连接的时间间隔
})

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>

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:
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