WebSocket断线重连

WebSocket断线重连 即时通讯 心跳重连
废话不多说,直接上代码.

$scope.timeout = 10800,//3分钟发一次心跳
$scope.timeoutObj = null,
$scope.serverTimeoutObj = null,
$scope.init = function() {
    $scope.lockReconnect = false,
    $scope.wsUrl = "wss://xxx:8888";
    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function() {
        ws.close();
    }
    //创建WebSocket对象
    $scope.createWebSocket = function() {
        try {
            if(window.WebSocket || window.MozWebSocket) {
                ws = new WebSocket($scope.wsUrl);
            }
            $scope.initEventHandle();
        } catch(e) {
            $scope.reconnectWebSocket($scope.wsUrl);
        }
    },
    $scope.initEventHandle = function() {
        /*** 连接建立时触发  */
        ws.onopen = function(e) {
            //发送登录信息
            msg = new Object();
            ws.send('xxx');

            $scope.heartCheckWebSocket(); //心跳检测重置
        };
        ws.onmessage = function(e) {
            $scope.heartCheckWebSocket(); //如果获取到消息,心跳检测重置
            //拿到任何消息都说明当前连接是正常的

            $scope.handMsg(e.data);
        };
        ws.onclose = function(e) {
            $scope.reconnectWebSocket($scope.wsUrl);
            //console.log("服务器拒绝了连接. 请检查服务器是否启动");
        };
        ws.onerror = function(e) {
            $scope.reconnectWebSocket($scope.wsUrl);
            //console.log("连接已断开,请刷新页面重新登录。");
        };
    },
    //处理消息
    $scope.handMsg = function(eventData) {
        if(!eventData) return;

        if(eventData == "close") {
            $scope.reconnectWebSocket($scope.wsUrl);
            //这里要注意onclose的第一个参数必须是1000或者3000—4999
            //console.log("服务器通知关闭");
        } else {
            //这里收到后端返回一个心跳消息,如果data返回空,则说明连接正常,到此停止处理
            //这里是你要写的逻辑代码
        }
    },
    //重连
    $scope.reconnectWebSocket = function() {
        if($scope.lockReconnect) return;
        $scope.lockReconnect = true;
        setTimeout(function() {
            $scope.createWebSocket(wsUrl);
            $scope.lockReconnect = false;
        }, 2000);
    },
    //心跳检测
    $scope.heartCheckWebSocket = function() {
        //重置
        $timeout.cancel($scope.timeoutObj);
        $timeout.cancel($scope.serverTimeoutObj);
        //开启
        $scope.timeoutObj = $timeout(function() {
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            //onmessage拿到返回的心跳就说明连接正常
            //发送登录信息
            msg = new Object();
            ws.send('xxx');
            $scope.serverTimeoutObj = $timeout(function() {
                //如果超过一定时间还没重置,说明后端主动断开了
                //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                ws.close();
            }, $scope.timeout);
        }, $scope.timeout);
    }
}

你可能感兴趣的:(WebSocket)