<script>
//websocekt教程
//https://www.ruanyifeng.com/blog/2017/05/websocket.html
//心跳流程(不是一上来就开始心跳检测的):
//InitWs 执行
// 连接成功
// 1.先触发onopen函数
// 2.触发Heartbeat
// 3.服务端返回心跳监测数据,执行WsOnMessage
// 3.触发Reset
// 4.Reset 回调 Heartbeat 即变成死循环 不停的心跳检测
// 连接失败(重连机制)
// 1.先触发onerror;再触发onclose
// 2.执行Reconnect1;执行Reconnect2(但因为lockReconnect变量的原因直接return,避免循环InitWS)
var Ws_readyState = {
0: 'CONNECTING',
1: 'OPEN',
2: 'CLOSING',
3: 'CLOSED',
}
var TimeOut = 5 * 1000///5秒一次心跳
var lockReconnect = false;//是否真正建立连接
var timeoutObj = null;
var serverTimeoutObj = null;
var timeoutnum = null;
var socket = null;
var wsUrl = 'ws://localhost:8765'
function InitWs(wsUrl) {
socket = new WebSocket(wsUrl);
socket.onopen = WsOnOpen;
socket.onmessage = WsOnMessage;
socket.onerror = WsOnError;
socket.onclose = WsOnClose;
}
function WsOnOpen() {
console.log("WebSocket连接成功");
//核心步骤1:开启心跳
Heartbeat();
}
function WsOnMessage(e) {
console.log(e.data);
//核心步骤2:收到服务器信息,心跳重置
Reset();
}
function WsOnError() {
//错误
console.log("WebSocket连接发生错误");
//重连
Reconnect();
console.log("OnError");
}
function WsOnClose() {
//关闭
console.log("WebSocket关闭");
//重连
Reconnect();
console.log("OnClose");
}
function Reconnect() {
//重连websocket
if (lockReconnect) {
return;
}
//避免重复Reconnect
lockReconnect = true;
timeoutnum && clearTimeout(timeoutnum)
timeoutnum = setTimeout(function () {
InitWs(wsUrl);
lockReconnect = false;
}, TimeOut)
}
function Heartbeat() {
//心跳包
console.log('ws 心跳包')
let __num = 3;
timeoutObj && clearTimeout(timeoutObj)
serverTimeoutObj && clearTimeout(serverTimeoutObj)
timeOutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (socket.readyState === 1) {
//连接正常
socket.send("heartCheck");
} else {
//否则重连
console.log('545')
Reconnect()
}
serverTimeOutObj = setTimeout(function () {
__num--;
if (__num === 0) {
Reconnect()
}
}, TimeOut)
}, TimeOut)
}
function Reset() {
console.log('Reset心跳');
//清除时间
clearTimeout(timeoutObj);
clearTimeout(serverTimeoutObj);
//重启心跳
Heartbeat();
}
</script>
<script>
//使用
InitWs(wsUrl)
</script>