用 js 写的 WebSocketHeartBeat,心跳检测,断线重连

it2024-12-07  15

用js写的WebSocketHeartBeat,心跳检测代码 <script> var ws;//websocket实例 var lockReconnect = false;//避免重复连接 var wsUrl = 'ws://localhost:8811'; function createWebSocket(url) { try { ws = new WebSocket(url); initEventHandle(); } catch (e) { reconnect(url); } } function initEventHandle() { //连接关闭 - 重连 ws.onclose = function (event) { console.log('onclose:' + event.data) reconnect(wsUrl); }; //连接异常 - 重连 ws.onerror = function (event) { console.log('onerror:' + event.data); reconnect(wsUrl); }; //连接成功 - 发送心跳消息 ws.onopen = function () { //保持连接:每60秒发送一个消息 setInterval(function () { ws.send('{"user_id": 0,"cmd_type":0,"content":"HeartBeat Message"}'); }, 60000); }; ws.onmessage = function(event){ try { let obj = JSON.parse(event.data); if (typeof obj == 'object' && obj) { //处理服务端返回的数据对象 obj:弹出消息框,内容支持点击... } } catch (e) { console.log('catch - error event:' + event.data + ' parse json error !!!' + e); } }.bind(this); } //重连操作 function reconnect(url) { if(lockReconnect){ return; } lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 setTimeout(function () { createWebSocket(url); lockReconnect = false; }, 10000); //10秒后重连 } //调用websocket createWebSocket(wsUrl); </script>
最新回复(0)