1. 在utils下面新建websocket.js
class WebsocketConn { constructor(url, cb) { this.cb = cb; this.url = url this.ws = null; this.lockReconnect = false; //避免ws重复连接 this.timeout = 30000; // 心跳检测时间 this.heartCheckTimer = null // 心跳检测定时器 this.heartCheckServerTimer = null; } heartCheckToReset() { clearTimeout(this.heartCheckTimer); clearTimeout(this.heartCheckServerTimer); return this; } heartCheckToStart() { this.heartCheckTimer = setTimeout(() => { //这里发送一个心跳,后端收到后,返回一个心跳消息, //onmessage 拿到返回的心跳就说明连接正常 this.ws.send("ping"); console.log("ping!") this.heartCheckServerTimer = setTimeout(() => {//如果超过一定时间还没重置,说明后端主动断开了 this.ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次 }, this.timeout) }, this.timeout) } create() { try{ if('WebSocket' in window){ this.ws = new WebSocket(this.url); } this.initEventHandle(); }catch(e){ this.reconnect(this.url); console.log(e); } } initEventHandle() { this.ws.onclose = () => { this.reconnect(this.url); console.log("websocket 连接关闭!"+ new Date().toLocaleString()); }; this.ws.onerror = () => { this.reconnect(this.url); console.log("websocket 连接错误!"); }; this.ws.onopen = () => { this.heartCheckToReset().heartCheckToStart(); //心跳检测重置 console.log("websocket 连接成功!"+new Date().toLocaleString()); }; this.ws.onmessage = (event) => { //如果获取到消息,心跳检测重置 this.heartCheckToReset().heartCheckToStart(); //拿到任何消息都说明当前连接是正常的 this.cb(); console.log("websocket 收到消息啦:" + event.data); }; } reconnect() { console.log("重新连接") if(this.lockReconnect) return; this.lockReconnect = true; setTimeout(() => { //重连,设置延迟避免请求过多 this.create(this.url); this.lockReconnect = false; }, 2000); } close() { this.ws.close(); } } export default WebsocketConn
2. 在组件中使用
1)引入
import WebsocketConn from "@/utils/websocket";
2)定义data
data: function () { return { websocket: null, } }
3)创建
createWebSocket() { let _this = this; let _wsurl = `${httpConfig.wsHost}api/websocket_service/v1/ws/get/business?business_id=${localStorage.businessId}&session_id=${localStorage.sessionId}` let _getMessage = () => { var msg = JSON.parse(event.data); if ((msg.code == 600 || msg.code == 601) && msg.result.data.length > 0 && !msg.result.data[0].withdrawalUserId) { _this.$router.go(0); } else { console.log(msg.code); } } _this.websocket = new WebsocketConn(_wsurl, _getMessage); _this.websocket.create(); },
4)销毁
destroyed() { this.websocket.close(); },