关于html:html-h5-vue-websocket-断链-心跳-个人笔记

40次阅读

共计 1772 个字符,预计需要花费 5 分钟才能阅读完成。

let webSocket = null;
let mAudio = null;
let webSocketStateInterval = null;
let heartInterval = null;
let number = 3;
let _closeType = false; // true 被动挂断 false 被动挂断

export default {initWebsocket() {
        let _that = this;
        let userInfo = JSON.parse(localStorage.getItem("userInfo"));
        let _url = process.env.VUE_APP_socketURL + userInfo.id;
        webSocket = new WebSocket(_url);
        webSocket.onopen = function(event) {// console.log("webSocket onopen ----->", event);

            heartInterval = setInterval(function(){webSocket.send(JSON.stringify({cmd: 100}));
            }, 10000);

            webSocketStateInterval = setInterval(function(){switch (webSocket.readyState) {
                    case WebSocket.CONNECTING:
                        console.log("webSocket 连贯中 ---->");
                        break;
                    case WebSocket.OPEN:
                        console.log("webSocket 关上中 ---->");
                        break;
                    case WebSocket.CLOSING:
                        console.log("webSocket 敞开中 ---->");
                        break;
                    case WebSocket.CLOSED:
                        console.log("webSocket 敞开胜利 ---->");
                        if(webSocketStateInterval){clearInterval(webSocketStateInterval);
                        }
                        if(_closeType == false){_that.initWebsocket();
                            // number--; if(number === 0) {webSocket.close();}
                        }
                        break;
                    default:
                        console.log("webSocket-------");
                        break;
                }
            }, 2000);
        };
        webSocket.onmessage = function(event) {// console.log("webSocket onmessage ----->", event);
            let message = JSON.parse(event.data);
            // console.log("message----->", message);
            if (message.cmd == 100) {console.log("100- 心跳中 ------", message.msg);
            }
        };
        webSocket.onerror = function(event) {console.log("webSocket onerror ----->", event);
            _that.initWebsocket();};
        webSocket.onclose = function(event) {console.log("webSocket onclose --->", event);
            if(_closeType){if(webSocketStateInterval){clearInterval(webSocketStateInterval);
                }
            }
            if(heartInterval){clearInterval(heartInterval);
            }
            _closeType = false;
        };
        // return new Promise((resolve, reject) => {resolve()});
    },
    sendWebSocket(text) {webSocket.send(JSON.stringify(text));
    },
    closeWebSocket(closeType) {
        _closeType = closeType;
        webSocket.close();},
    closeAudio() {mAudio.pause();
    }
}

正文完
 0