前端原生socket封装

直接上代码

var _this = '';

function socket(url) {
    this.url = url;
    this.websocket = '';
    this.msg = '';
    this.lockReconnect = false;
}
// 初始化
socket.prototype.initWebsocket = function() {
        if ('WebSocket' in window) {
            _this = this;
            this.websocket = new WebSocket(this.url);
            this.websocket.onerror = this.onError;
            this.websocket.onmessage = this.onMessage;
            this.websocket.onopen = this.onOpen;
            this.websocket.onclose = this.onClose;
        } else {
            console.log('错误:浏览器不支持websocket,请更换新版浏览器');
        }
    }
    // 连接异常处理
socket.prototype.onError = function() {
        _this.msg = "websocket错误," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
        console.warn(_this.msg);
        // 重新连接
        _this.reconnect();
    }
    // 接收到消息处理
socket.prototype.onMessage = function(event) {
        if (event.data == 'ok') {
            heartCheck.start();
            return;
        }
        window.dispatchEvent(new CustomEvent('onmessageWS', {
            detail: {
                data: event.data
            }
        }))

        // 通过下面接受消息 下面这个在其他js里
        // window.addEventListener("onmessageWS", function(e) {
        //     console.log(e.detail)
        // })
    }
    // 关闭连接处理
socket.prototype.onClose = function(e) {
        _this.msg = "websocket断开连接:" + new Date().toTimeString();
        console.log(_this.msg);
        console.log('日志:' + e.code + ' ' + e.reason + ' ' + e.wasClean);
        if (e.code != 1000 && e.code != 1006) {
            // 重新连接
            _this.reconnect();
        }
    }
    // 打开连接处理
socket.prototype.onOpen = function() {
        _this.msg = "websocket连接成功," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
        console.log(_this.msg);
        _this.websocket.send('加入websocket连接');
        // 心跳检测重置
        heartCheck.start();
    }
    // 主动关闭连接
socket.prototype.close = function() {
        // 关闭socket连接
        _this.websocket.close();
        _this.lockReconnect = true;
    }
    // socket 重连
socket.prototype.reconnect = function() {
    // 已经重连则取消后续操作
    if (_this.lockReconnect) return;
    _this.lockReconnect = true;
    // 没连接上会一直重连,设置延迟避免请求过多
    tt && clearTimeout(tt);
    _this.msg = '正在进行重连:' + new Date().toTimeString();
    console.log(_this.msg);

    var tt = setTimeout(function() {
        _this.initWebsocket();
        _this.lockReconnect = false;
    }, 5000);
}

let heartCheck = {
    timeout: 5000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function() {
        let self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function() {
            console.log('check socket heart beat……');
            //发送测试信息,后端收到后,返回一个消息,
            _this.websocket.send("ping");
            self.serverTimeoutObj = setTimeout(function() {
                _this.websocket.onerror();
            }, self.timeout)
        }, this.timeout);
    }
}

export { socket }

调用

 sk = new socket(`ws://255,255,255,255:8080/socket/xxxx`);
    sk.initWebsocket();

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值