import { getWebsocketUrl } from '@/api/ajax'
export default function (callback) {
const path = getWebsocketUrl();
const jspCode = 100;
let websocket;
let lockReconnect = false, tt;
createWebSocket();
function createWebSocket() {
try {
if ('WebSocket' in window) {
websocket = new WebSocket((path + "/" + jspCode).replace("http", "ws").replace("https", "ws"));
} else {
alert('当前浏览器 Not support websocket!')
}
init();
} catch (e) {
console.log('建立连接失败,尝试重连!' + e);
reconnect();
}
}
function init() {
websocket.onopen = function (event) {
console.log("WebSocket:已连接");
heartCheck.reset().start();
};
websocket.onmessage = function (event) {
callback(event)
heartCheck.reset().start();
};
websocket.onerror = function (event) {
console.log("WebSocket:发生错误");
reconnect();
};
websocket.onclose = function (event) {
console.log("WebSocket:已关闭");
heartCheck.reset();
reconnect();
};
window.onbeforeunload = function () {
closeWebSocket();
};
function closeWebSocket() {
websocket.close();
}
function send(message) {
websocket.send('{"msg":"' + message + '"}');
}
}
function reconnect() {
if (lockReconnect) {
return;
}
lockReconnect = true;
tt && clearTimeout(tt);
tt = setTimeout(function () {
console.log('重连中...');
lockReconnect = false;
createWebSocket();
}, 4000);
}
let heartCheck = {
timeout: 5000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
let self = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function () {
websocket.send("HeartBeat");
self.serverTimeoutObj = setTimeout(function () {
console.log('关闭服务');
websocket.close();
}, self.timeout)
}, this.timeout)
}
};
}
使用方式
import websocket from '@/utils/websocket.js';
websocket((data) => {
console.log(data)
})