这是对以前一篇文章的升级迭代版。因为需求有所改动就做了很多的优化。 话不多说直接上代码:
1:因为要做到心跳时间可配置,就写了个txt,运维人员可以修改
这里关注heart_time就行了
2:ajax去读取时间,调用心跳函数
ngOnInit(): void {
if(!sessionStorage.getItem('heart')){
let n = 10;
const that = this;
sessionStorage.setItem('heart','true');
$.ajax({
type: 'GET',
url: 'download.txt',
dataType: 'json',
success: function(data){
n = parseInt(data.heart_time,10)*1000;
that.setHeartWs(n);
},
error: function(e){
that.msg.warning('未知错误,请联系管理员');
}
})
}
window.onbeforeunload = function(){
sessionStorage.removeItem('heart');
}
}
3:重点来了,心跳函数
setHeartWs(n:number){
const that = this;
const token_:any = this.tokenService.getPayload();
let message = `${token_.userId}_${token_.clientIp}`;
let lockReconnect = false;
let protocol: any;
if (window.location.protocol === 'http:') {
protocol = window.location.protocol.replace('http', 'ws');
} else if (window.location.protocol === 'https:') {
protocol = window.location.protocol.replace('https', 'wss');
}
const host = window.location.host;
const path = 'ping';
let ws:WebSocket;
let tt = 0;
function creatWs(){
try{
ws = new WebSocket(`${protocol}//${host}/${path}`);
init();
}catch(e){
reconnect();
}
}
function init(){
ws.onopen = function(){
ws.send(message);
heartCheck.start();
};
ws.onmessage = function(event){
heartCheck.start();
}
ws.onerror = function(event){
heartCheck.start();
}
ws.onclose = function(event){
if(sessionStorage.getItem('heart')){
heartCheck.start();
}
}
}
function reconnect() {
if(lockReconnect) {
return;
};
lockReconnect = true;
tt && clearTimeout(tt);
tt = setTimeout(function () {
creatWs();
lockReconnect = false;
}, n);
}
var heartCheck = {
timeout: n,
timeoutObj: null,
serverTimeoutObj: null,
start: function(){
const that = this;
that.timeoutObj && clearTimeout(that.timeoutObj);
that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
if(sessionStorage.getItem('heart')){
that.timeoutObj = setTimeout(function(){
if(ws&&ws.readyState<3){
ws.send(message);
}else{
lockReconnect = false;
reconnect();
}
}, that.timeout)
}
}
}
creatWs();
}
这样基本上就可以满足项目里心跳功能的实现了。 工作上的总结,能有所帮助就最好了。 如果有什么问题,欢迎留言交流。
|