美文网首页
前端websocket连接

前端websocket连接

作者: 欧_汤姆 | 来源:发表于2019-08-03 09:37 被阅读0次
<script type="text/javascript">
    var cnt=0;
    var lockReconnect = false;  //避免ws重复连接
    var ws = null;          // 判断当前浏览器是否支持WebSocket
    var wsUrl=webSocketURL;
    createWebSocket(wsUrl);
    function createWebSocket(url) {
        try {
            if ('WebSocket' in window) {
                ws = new WebSocket(url);
            } else if ('MozWebSocket' in window) {
                ws = new MozWebSocket(url);
            } else {
                layer.open({
                    content: "当前浏览器不支持WebSocket",
                    type: 1,
                    // icon: 0,
                    time: 0, closeBtn: 1, btn: 0, title: "提示信息", isOutAnim:true,anim: 2,area: ['400px', '300px'],shade: 0.2,tipsMore: true
                });
            }
            initEventHandle();
        } catch (e) {
            reconnect(url);
        }
    }
   // var socketsend;
    function initEventHandle() {
        ws.onclose = function () {
            console.log("llws连接关闭!" + CurentTime());
            reconnect(wsUrl);
        };
        ws.onerror = function () {
            console.log("llws连接错误!");
            reconnect(wsUrl);
        };
        ws.onopen = function () {
            // heartCheck.reset().start();      //心跳检测重置
            console.info("llws连接成功!" + CurentTime());
        };
        ws.onmessage = function (evt) {    //如果获取到消息,心跳检测重置
            console.info("llws连接成功" + evt.data);
           var data = $.parseJSON(evt.data);
            if(data.order==0){
                addOpenRecord();//开门记录
            }
            if(data.order==1){
                addStranger(data.data);//推送陌生人
            }
            if(data.order==2){
                //推送命中内部人员实时照片
                addInsider(data.data);
            }
            if(data.order==3){//陌生人记录
                addStrangerRecord();
            }

        }
    }
// 监听窗口关闭事件,当窗口关闭时,
// 主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        ws.close();
    }
    function reconnect(url) {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () {
            //没连接上会一直重连,设置延迟避免请求过多
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }
    //心跳检测
    var heartCheck = {
        timeout: 3000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳,后端收到后,返回一个心跳消息,
                //onmessage拿到返回的心跳就说明连接正常
                ws.send("ping");
                console.log("ping!")
                self.serverTimeoutObj = setTimeout(function () {
                    //如果超过一定时间还没重置,说明后端主动断开了
                    //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    ws.close();
                },self.timeout)
            },this.timeout)
        }
    }
    function CurentTime(){
        var now = new Date();
        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var hh = now.getHours();            //时
        var mm = now.getMinutes();          //分
        var ss=now.getSeconds();     // 获取当前秒数(0-59)
        if(month < 10)
            month = "0"+month;
        if(day < 10)
            day = "0"+day;
        if(hh < 10)
            hh = "0"+hh;
        if(mm < 10)
            mm = "0"+mm;
        if(ss < 10)
            ss = "0"+ss;
        clock=year+"-"+month+"-"+day+" "+hh+":"+mm+":"+ss;
        return(clock);
    }

</script>

相关文章

网友评论

      本文标题:前端websocket连接

      本文链接:https://www.haomeiwen.com/subject/migddctx.html