How to use WebSocket to achieve real-time communication in Vue
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
- 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.
- 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. .
- 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
- 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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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

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.

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.

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

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 <script> tag in the HTML file that refers to the Vue file.

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.
