浏览器端WebSocket简单封装代码分享,支持异常重连

之前做项目接触到WebSocket都是使用Nodejs的socket.io库来实现的,最近做项目,需要使用WebSocket做简单的轮询,可是后端是使用Java编写的,需求简单,不过需要支持在异常断连情况下支持重连,于是就对浏览器端WebSocket做了简单的封装。
示例代码放在:https://gitee.com/baojuhua/JS-snippets/tree/master/JavaScript/WSclient

代码

WSclient.js

class WSclient {
    constructor(url, opt) {
        if (url.constructor === Object) {
            opt = url;
            this.url = url = opt.url;
        }
        this.evtStack = {
            'close': [this.reconnection.bind(this)],
            'error': [],
            'message': [],
            'open': [(function () { this.reconnectionCount = 0; this.reconnectionTimer = null; }).bind(this)]
        };
        this.normalClose = false;//正常关闭标识
        this.EVENTS = Object.keys(this.evtStack);
        this.opt = Object.assign({
            reconnection: true,//断线重连
            reconnectionAttempts: Infinity,//重连次数
            reconnectionDelay: 1000,// 重连延时,1秒后尝试
            autoConnect: true,//创建自动连接
        }, opt && opt.constructor === Object ? opt : {});
        this.reconnectionCount = 0;//实际重试次数
        this.send = this.socket = this.reconnectionTimer = null;
        if (this.opt.autoConnect && url) this.connect(url);
    }
    reconnection() {//重连
        if (!this.normalClose && this.opt.reconnection) {//非正常关闭&&需要重启
            if (this.opt.reconnectionAttempts > this.reconnectionCount) {//重试次数
                this.reconnectionCount++;
                clearInterval(this.reconnectionTimer);
                this.reconnectionTimer = setTimeout(this.connect.bind(this), this.opt.reconnectionDelay);
            }
        }
    }
    connect(url) {// 连接
        if (this.socket) {
            if (this.socket.readyState == this.socket.CLOSED) delete this.socket;//
            else this.socket.close();//关闭连接
        }
        this.url = url || this.url;
        this.socket = new WebSocket(this.url);
        this.send = this.socket.send;
        this.normalClose = false;
        this.EVENTS.forEach(k => { this.evtStack[k].forEach(f => { this.socket.addEventListener(k, f) }) });//事件绑定
    }
    on(evt, _fun) {
        if (this.EVENTS.indexOf(evt) >= 0) {
            this.evtStack[evt].push(_fun);
            if (this.socket) this.socket.addEventListener(evt, _fun);
        }
    }
    close() {
        this.normalClose = true;//正常关闭
        this.socket.close(...arguments);
    }
}

浏览器端引用

<script src="./WSclient.js"></script>

初始化示例

示例1

const socket = new WSclient(`ws://127.0.0.1:3001`);

示例2

const socket = new WSclient(`ws://127.0.0.1:3001`,{
    reconnection: true,//断线重连
    reconnectionAttempts: 3,//重连次数
    reconnectionDelay: 1000,// 重连延时,1秒后尝试 
});

示例3

const socket = new WSclient({
    url: `ws://127.0.0.1:3001`,
    reconnection: true,//断线重连
    reconnectionAttempts: 3,//重连次数
    reconnectionDelay: 1000,// 重连延时,1秒后尝试
    autoConnect: false//创建自动连接
}); 

socket.connect();//手动连接

使用示例

// if ('WebSocket' in window) {
    const socket = new WSclient(`ws://127.0.0.1:3001`);

    socket.on('open', function (event) {
        console.log("连接成功!!")
        socket.send('Hello Server!');
    });

    socket.on('close', function (event) {
        console.log('关闭连接')
    });

    socket.on('message', function (event) {
        console.log('信息:', event.data);
    });
// }