在线客服系统,JS定时器实现访客长时间无回话,自动断开websocket链接

客服系统的聊天界面,当访客进入后,会自动连接后端websocket服务。该服务有断线重连机制,因此如果前端不主动关闭连接,并且不进行重连操作,那么websocket连接会一直保持。

这样会占用不少的资源,并且会误导客服人员。因此,需要使用JS定时查看访客回复的时间,如果超过一段时间了,就主动关闭websocket连接

 

其实,主要就是每次发言时,都更新一下活动时间。

设置一个定时器,每隔10秒检查下当前时间与活动时间的差值,超过了一定时间,就关闭连接,并且关闭重连机制

定时器部分如下面参考代码:

//超时关闭
            checkTimeout:function(){
                var _this=this;
                this.timeTool.timeoutTimer=setInterval(function(){
                    if ((Date.now() - _this.timeTool.activeTime) >= _this.timeTool.timeoutTime) {
                        console.log("访客长时间无回话");
                        if(_this.websocket.instance!=null){
                            _this.websocket.serverReturnClose=true;
                            _this.websocket.instance.close();
                        } 
                    }
                },10000);
            },

 

每次访客回话后,更新下活动时间

this.timeTool.activeTime=Date.now();

 

重连机制部分,对前面的变量进行了判断

// 尝试重连
            reconnect(){
                var _this=this;
                if (_this.websocket.serverReturnClose) {
                    console.log('停止重连');
                    return;
                }
            },