新增 - 更好的心跳包检测

This commit is contained in:
suwings 2018-05-22 23:04:55 +08:00
parent ad4befa826
commit 409ae4d86f
2 changed files with 34 additions and 5 deletions

View File

@ -4,10 +4,11 @@
var DEBUG = false; //Websocket DEBUG var DEBUG = false; //Websocket DEBUG
//from @BBleae //from @BBleae
//10 秒自动发送一次心跳包,此时间不可改变
function wsHeartBeatPackage(ws) { function wsHeartBeatPackage(ws) {
setInterval(function () { setInterval(function () {
ws.sendMsg("HeartBeatPackage", ""); ws.sendMsg("HBPackage", "");
}, 10000); }, 1000 * 10);
} }
var ify = '\n\n'; var ify = '\n\n';

View File

@ -61,7 +61,8 @@ router.ws('/ws', function (ws, req) {
token = token.trim(); token = token.trim();
let username = null; let username = null;
let status = true; let status = false;
let wsAliveHBCount = 5;
//临时的会话id 一般只用于内部验证是否是这个tcp链接 //临时的会话id 一般只用于内部验证是否是这个tcp链接
let uid = permssion.randomString(12) + Date.parse(new Date()).toString(); let uid = permssion.randomString(12) + Date.parse(new Date()).toString();
@ -122,7 +123,8 @@ router.ws('/ws', function (ws, req) {
return; return;
} }
//状态标识
status = true;
//放置全局在线列表 //放置全局在线列表
MCSERVER.allSockets[uid] = WsSession; MCSERVER.allSockets[uid] = WsSession;
@ -132,6 +134,7 @@ router.ws('/ws', function (ws, req) {
//检查通过.. //检查通过..
MCSERVER.log('[ WebSocket INIT ]', ' 用户:', username, "与服务器建立链接"); MCSERVER.log('[ WebSocket INIT ]', ' 用户:', username, "与服务器建立链接");
//数据到达事件 //数据到达事件
ws.on('message', function (data) { ws.on('message', function (data) {
try { try {
@ -163,6 +166,13 @@ router.ws('/ws', function (ws, req) {
reqHeaderObj = JSON.parse(reqHeader); reqHeaderObj = JSON.parse(reqHeader);
if (!reqHeaderObj) return; if (!reqHeaderObj) return;
//Websocket 心跳包 | 前端 10 秒递增链接健康指数
//当网络延迟特别高时,也能很好的降低指数. 将来指数够低时,将自动优化数据的发送
if (reqHeaderObj['RequestValue'] == "HBPackage") {
status = true;
wsAliveHBCount < 10 && wsAliveHBCount++;
}
WebSocketObserver().emit('ws/req', { WebSocketObserver().emit('ws/req', {
ws: ws, ws: ws,
req: req, req: req,
@ -178,8 +188,26 @@ router.ws('/ws', function (ws, req) {
} }
}); });
//关闭事件
ws.on('close', function () { ws.on('close', function () {
WebSocketClose();
});
//Websocket 心跳包检查 | 12 秒递减一个链接健康指数
var HBMask = setInterval(() => {
if (wsAliveHBCount <= 0) {
MCSERVER.log('[ WebSocket HBPackage ]', '用户', username, '长时间未响应心跳包 | 已自动断开');
WebSocketClose();
}
wsAliveHBCount--;
}, 1000 * 12)
//Websocket 关闭函数
function WebSocketClose() {
if (!status) return;
ws.close();
clearInterval(HBMask);
status = false; status = false;
//再删一次,保险 //再删一次,保险
@ -194,7 +222,7 @@ router.ws('/ws', function (ws, req) {
} }
delete MCSERVER.allSockets[uid]; delete MCSERVER.allSockets[uid];
MCSERVER.log('[ WebSocket CLOSE ]', '用户', username, '已经断开链接'); MCSERVER.log('[ WebSocket CLOSE ]', '用户', username, '已经断开链接');
}); }
}); });