前端应对报错 WebSocket is already in CLOSING or CLOSED state.

今天写WebSocket的时候突然报错   WebSocket is already in CLOSING or CLOSED state.  他的意思是 WebSocket已经处于关闭或关闭状态。
出现这个问题有很多原因,对于前端来说一直报这个错误是因为,已经断开连接了 还是再send数据,这时候眼看一下是否断开连接  ,如果断开就重//打开socket

    chatObj.openWebSocket = function() {
        var webSocket = new WebSocket("");
        webSocket.onerror = function (event) {
            //alert(event.data);
        };
        webSocket.onopen = function (event) {
            //心跳包
            g_chatInterval = setInterval(() => {
                var msg = {header:"heartbeat"}
                webSocket.send(JSON.stringify(msg))
            }, 2000); 
        };
        webSocket.onclose = function (event) {
            console.log('连接已断开,正在重连');
            clearInterval(g_chatInterval);
            chatObj.openWebSocket();
        }

        webSocket.onmessage = function (event) {
            console.log(event.data)
           
        };
    }

 

posted @ 2023-02-21 16:12  黑白棋学弟  阅读(3570)  评论(0编辑  收藏  举报