webSocket 类封装
webSocket.js 文件代码如下:
// webSocket类
class Socket {
// 接收消息参数
message = null;
constructor(options) {
const { url, heartTime, reconnectTime } = options;
const classSelf = this;
this.reconnectTime = reconnectTime || 5000; // 重连时间
this.lockReconnect = false;//避免重复连接
this.ws = null; //WebSocket的引用
this.wsUrl = url; //这个要与后端提供的相同
//心跳检测
this.heartCheck = {
timeout: heartTime || 15000,//毫秒
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
const self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息, 【发送格式与后端沟通】
//onmessage拿到返回的心跳就说明连接正常
classSelf.ws.send(JSON.stringify({ type: "HeartBeat"