使用場景:
在專案開發中,后端需要處理一連串的邏輯,或者等待第三方的資料回傳來進行處理之后在回傳給前端,可能時間會很長,而且前端也不知道后端什么時候能處理好(時間長的話會達到10分鐘左右),如果采用普通的HTTP連接,前后端無法一直保持聯系,麻煩的時候可能還需要采用輪詢的機制,所以使用WebSocket連接效果還是比較好的,
使用時間:
在界面加載完之后,建上WebSocket連接,此時前端還可以發送普通的HTTP的請求,等到后端處理完之后,通過建立的WebSocket連接返給前端,前端根據回傳的資料進行對應的操作,
代碼展示:
<template></template><script>export default { data() { return{ // 用戶Id userId:'', appid:'', // 事件型別 type:'', msg:'', wsUrl:'' } }, methods: { //初始化weosocket initWebSocket() { if (typeof WebSocket === "undefined") { alert("您的瀏覽器不支持WebSocket"); return false; } const wsuri = 'ws://(后端WebSocket地址)/websocket/' + this.userId + '/' + this.appid // websocket地址 this.websock = new WebSocket(wsuri); this.websock.onopen = this.websocketonopen; this.websock.onmessage = this.websocketonmessage; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, //連接成功 websocketonopen() { console.log("WebSocket連接成功"); // 添加心跳檢測,每30秒發一次資料,防止連接斷開(這跟服務器的設定有關,如果服務器沒有設定每隔多長時間不發訊息斷開,可以不進行心跳設定) let self = this; this.timer = setInterval(() => { try { self.websock.send('test') console.log('發送訊息'); }catch(err){ console.log('斷開了:' + err); self.connection() } }, 30000) }, //接收后端回傳的資料,可以根據需要進行處理 websocketonmessage(e) { var vm = this; let data1Json = JSON.parse(e.data); console.log(data1Json); }, //連接建立失敗重連 websocketonerror(e) { console.log(`連接失敗的資訊:`, e); this.initWebSocket(); // 連接失敗后嘗試重新連接 }, //關閉連接 websocketclose(e) { console.log("斷開連接", e); } }, created() { if (this.websock) { this.websock.close(); // 關閉websocket連接 } this.initWebSocket(); }, destroyed() { //頁面銷毀時關閉ws連接 if (this.websock) { this.websock.close(); // 關閉websocket } }};</script>問題回顧:
在實際使用的時候遇到的問題:有的時候頁面鏈接還沒有建立上,但是后端已經把資料都處理好了,這個時候推給前端,前端接收不到,
解決方案:
1)簡單的方法:讓后端延遲幾秒再推
優勢:簡單
劣勢:降低了性能
2)優化之后的方法:使用Redis保存用戶的登錄狀態,快取這個用戶的資料,等到建立連接之后再推,推完就清空Redis
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/31328.html
標籤:HTML5
