vue專案中使用websocket的實現
阿新 • • 發佈:2022-01-30
什麼是websocket?
“WebSocket 是 HTML5 開始提供的一種在單個 TCP 連線上進行全雙工通訊的協議。
WebSocket 使得客戶端和伺服器之間的資料交換變得更加簡單,允許服務端主動向客戶端推送資料。在 WebSocket API 中,瀏覽器和伺服器只需要完成一次握手,兩者之間就直接可以建立永續性的連線,並進行雙向資料傳輸。
在 WebSocket API 中,瀏覽器和伺服器只需要做一個握手的動作,然後,瀏覽器和伺服器之間就形成了一條快速通道。兩者之間就直接可以資料互相傳送。”
1. 在utils下新建websocket.檔案
// import { showInfoMsg,showErrorMsg } from '@/utils/popInfowww.cppcns.com' import ElementUI from 'element-ui'; function initWebSocket(e) { console.log(e) const wsUri = WS_API + "/webSocket/" + e; this.socket = new WebSocket(wsUri)//這裡面的this都指向 this.socket.onerror = webSocketOnError; this.socket.onmessage = webSocketOnMessage; this.socket.onclose = closeWebsocket; } function webSocketOnError(e) { ElementUI.Notification({ title: '',message: "WebSocket連線發生錯誤" + 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: '',www.cppcns.com}); } } // 關閉websiocket function closeWebsocket() { console.log('連線已關閉...') } function close() { this.socket.close() // 關閉 websocket this.socket.onclose = function (e) { console.log(e)//監聽關閉事件 console.log('關閉') } } function webSocketSend(agentData) { this.socket.send(agentData); } export default { initWebSocket,close }
如果想重新整理重新連結websocket 可以在App.vue頁面裡添加個鉤子函式
mounted() { //當在任一路由頁面被重新整理時,便是根元件app被從新建立,此時能夠進行webSocket重連 //從localStorage中獲取使用者資訊,是登陸狀態則能夠進行webSocket重連 let token = localStorage.getItem("token"); if (token) { // userMessage = JSON.parse(userMessage)RFiQl; this.$websocket.initWebSocket(token); } },
客戶端主動關閉websocket 在關閉的地方觸發函式就可以
logout() { // localStorage.clear(); localStorage.removeItem("token"); this.$websocket.close(); this.$store.dispatch("LogOut").then(() => { location.reload(); }); },
注:$webSocket 是在main.js中全域性註冊了websocket.js檔案
到此這篇關於vue專案中使用websocket的實現的文章就介紹到這了,更多相關vue使用websocket內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!