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();