Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use websocket in vue projects

Shulou Source: shulou.com Published: 2022-06-01 10:15:54 11月20日 Update

This article will explain in detail how to use websocket in the vue project. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

What is websocket?

"WebSocket is a protocol that HTML5 began to provide for full-duplex communication over a single TCP connection.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In WebSocket API, only one handshake is needed between the browser and the server, and a persistent connection can be directly created between the browser and the server for two-way data transmission.

In WebSocket API, the browser and the server only need to shake hands, and then a fast channel is formed between the browser and the server. Data can be transmitted to each other directly between the two. "

1. Create a new websocket.js file under utils

/ / import {showInfoMsg, showErrorMsg} from'@ / utils/popInfo'import ElementUI from 'element-ui';function initWebSocket (e) {console.log (e) const wsUri = WS_API + "/ webSocket/" + e; this.socket = new WebSocket (wsUri) / / the this in here all points to vue this.socket.onerror = webSocketOnError; this.socket.onmessage = webSocketOnMessage; this.socket.onclose = closeWebsocket } function webSocketOnError (e) {ElementUI.Notification ({title:', message: "WebSocket connection error" + e, type: 'error', duration: 0,});} function webSocketOnMessage (e) {const data = JSON.parse (e.data) Console.log (data.msgType = = "INFO", data.msgType = "INFO") if (data.msgType = "INFO") {ElementUI.Notification ({title:', message: data.msg, type: 'success', duration: 3000,}) } else if (data.msgType = = "ERROR") {ElementUI.Notification ({title:', message: data.msg, type: 'error', duration: 0,}) }} / / close websiocketfunction closeWebsocket () {console.log ('connection closed...')} function close () {this.socket.close () / / close websocket this.socket.onclose = function (e) {console.log (e) / / listen for the close event console.log ('close')}} function webSocketSend (agentData) {this.socket.send (agentData);} export default {initWebSocket, close}

If you want to refresh and relink websocket, you can add a hook function to the App.vue page.

Mounted () {/ / when the routing page is refreshed, the root component app is re-established, and the webSocket reconnection can be performed / / the user information can be obtained from the localStorage, and the login status can be reconnected with webSocket let token = localStorage.getItem ("token"); if (token) {/ / userMessage = JSON.parse (userMessage); this.$websocket.initWebSocket (token);}}

The client actively closes the websocket and triggers the function where it is closed.

Logout () {/ / localStorage.clear (); localStorage.removeItem ("token"); this.$websocket.close (); this.$store.dispatch ("LogOut"). Then () = > {location.reload ();});}

Note: $webSocket registers the websocket.js file globally in main.js

This is the end of the article on "how to use websocket in the vue project". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Services between data servers clients clients browsers articles browsing projects initiatives functions files more pages good practical events information global Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS vpn Huawei Shulou Tech Info