前端应对报错 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 @   黑白棋学弟  阅读(3891)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示