用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秒后重连}//调用websocketcreateWebSocket(wsUrl);</script>