用js写的WebSocketHeartBeat,心跳检测代码
<script>
var ws;
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 () {
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) {
}
} 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);
}
createWebSocket(wsUrl);
</script>
转载请注明原文地址: https://lol.8miu.com/read-21081.html