其他分享
首页 > 其他分享> > js socket处理断网重连

js socket处理断网重连

作者:互联网

代码:

var socket; //websocket的实例
var lockReconnect = false; //避免重复连接
getwebsocket();
function getwebsocket() { //新建websocket的函数 页面初始化 断开连接时重新调用
    var wsUrl = 'ws://192.168.0.147:8080/api/v1/socket/order/wGk86yE7MShsN3DM2Q5m7t2NEzPS5zmE1634897413404' + window.token + '&djxh=' + window.djxh;
    socket = new WebSocket(wsUrl);
    socket.onerror = function(event) {
        console.log('websocket服务出错了');
        reconnect(wsUrl);
    };
    socket.onclose = function(event) {
        console.log('websocket服务关闭了');
        reconnect(wsUrl);
    };
    socket.onopen = function(event) {
        console.log('websocket连接成功');
        heartCheck.reset().start(); //传递信息
    };
    socket.onmessage = function(event) {
        //如果获取到消息,心跳检测重置
        //拿到任何消息都说明当前连接是正常的
        //console.log('websocket服务获得数据了');
        //接受消息后的UI变化
        doWithMsg(event.data);
        heartCheck.reset().start();
    };
    //收到消息推送
    function doWithMsg(msg) {
        // getdjxh()//这个函数是业务上面申请列表的函数 可以忽略
        // window.external.CallFun('receiveMsg');//这个也是
    }
}

function reconnect(url) {
    if (lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连,设置延迟避免请求过多
    setTimeout(function() {
        getwebsocket();
        lockReconnect = false;
    }, 2000);
}
//心跳检测
var heartCheck = {
    timeout: 60000, //60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function() {
        var self = this;
        this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            //onmessage拿到返回的心跳就说明连接正常
            socket.send("心跳测试");
            self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置,说明后端主动断开了
                socket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
}

标签:function,websocket,socket,断网,reconnect,var,重连,event
来源: https://blog.csdn.net/qq_42740797/article/details/120911464