vue 訊息推送 WebSocket
阿新 • • 發佈:2022-04-01
1、建立WebSocket.js檔案
2、設定連結
const url = "localhost:8080"
3、方法
class WebSocketClass { constructor() { this.instance = null; this.connect(); } static getInstance() { if (!this.instance) { this.instance = new WebSocketClass(); } return this.instance; } // 建立連線 connect() { this.ws = new WebSocket(url); this.ws.onopen = e => { this.heartCheck(); this.getMessage(); }; } // 心跳 heartCheck() { const _this = this; // 心跳狀態 this.state = setInterval(() => { if (_this.ws.readyState === 1) { _this.ws.send("/Heart"); } else { this.closeHandle(); // 重新連線 console.log("狀態未連線"); } }, 60000); } closeHandle() { if (this.state) { console.log(`斷開,重連websocket`); // 清除定時器; clearInterval(this.state); this.connect(); // 重連 } else { console.log(`websocket手動關閉,或者正在連線`); } } // 收/發信息 getMessage() { this.ws.onmessage = e => { if (e.data) { const newsData = JSON.parse(e.data); // 接收到訊息 console.log(`newsData`); } }; } // 關閉 close() { this.ws.close(); console.log("關閉連線"); } } export default WebSocketClass;
4、訊息狀態
// readyState
// 0 - 表示連線尚未建立。
// 1 - 表示連線已建立,可以進行通訊。
// 2 - 表示連線正在進行關閉。
// 3 - 表示連線已經關閉或者連線不能開啟。
5、呼叫(載入頁面中呼叫)
import WebSocketClass from "@/utils/websocket.js";
// 建立訊息連線
const ws = new WebSocketClass();
ws.getMessage();