make keepalive self-contained

This commit is contained in:
Romain Beaumont 2017-07-21 10:52:11 +02:00
parent a2598cefda
commit 8dd313b5de
No known key found for this signature in database
GPG Key ID: DB60E388B3BCF286
2 changed files with 19 additions and 12 deletions

View File

@ -1,8 +1,12 @@
module.exports=function(client,server,{kickTimeout = 30 * 1000,checkTimeoutInterval = 4 * 1000}) { module.exports=function(client,server,{
kickTimeout = 30 * 1000,
checkTimeoutInterval = 4 * 1000,
keepAlive : enableKeepAlive = true
}) {
let keepAlive = false; let keepAlive = false;
let lastKeepAlive = null; let lastKeepAlive = null;
client._keepAliveTimer = null; let keepAliveTimer = null;
let sendKeepAliveTime; let sendKeepAliveTime;
@ -27,11 +31,20 @@ module.exports=function(client,server,{kickTimeout = 30 * 1000,checkTimeoutInter
lastKeepAlive = new Date(); lastKeepAlive = new Date();
} }
client._startKeepAlive= () => { function startKeepAlive() {
keepAlive = true; keepAlive = true;
lastKeepAlive = new Date(); lastKeepAlive = new Date();
client._keepAliveTimer = setInterval(keepAliveLoop, checkTimeoutInterval); keepAliveTimer = setInterval(keepAliveLoop, checkTimeoutInterval);
client.on('keep_alive', onKeepAlive); client.on('keep_alive', onKeepAlive);
} }
if(enableKeepAlive) client.on('state',state => {
if(state === "play") {
startKeepAlive();
}
});
client.on('end', () => clearInterval(keepAliveTimer));
}; };

View File

@ -9,7 +9,6 @@ module.exports=function(client,server,options) {
const { const {
'online-mode' : onlineMode = true, 'online-mode' : onlineMode = true,
kickTimeout = 30 * 1000, kickTimeout = 30 * 1000,
keepAlive : enableKeepAlive = true,
errorHandler : clientErrorHandler=(client,err) => client.end(), errorHandler : clientErrorHandler=(client,err) => client.end(),
} = options; } = options;
@ -18,13 +17,9 @@ module.exports=function(client,server,options) {
client.on('error', function(err) { client.on('error', function(err) {
clientErrorHandler(client, err); clientErrorHandler(client, err);
}); });
client.on('end', onEnd); client.on('end', () => {
function onEnd() {
clearInterval(client._keepAliveTimer);
clearTimeout(loginKickTimer); clearTimeout(loginKickTimer);
} });
client.once('login_start', onLogin); client.once('login_start', onLogin);
@ -127,7 +122,6 @@ module.exports=function(client,server,options) {
client.write('success', {uuid: client.uuid, username: client.username}); client.write('success', {uuid: client.uuid, username: client.username});
client.state = states.PLAY; client.state = states.PLAY;
loggedIn = true; loggedIn = true;
if(enableKeepAlive) client._startKeepAlive();
clearTimeout(loginKickTimer); clearTimeout(loginKickTimer);
loginKickTimer = null; loginKickTimer = null;