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 lastKeepAlive = null;
client._keepAliveTimer = null;
let keepAliveTimer = null;
let sendKeepAliveTime;
@ -27,11 +31,20 @@ module.exports=function(client,server,{kickTimeout = 30 * 1000,checkTimeoutInter
lastKeepAlive = new Date();
}
client._startKeepAlive= () => {
function startKeepAlive() {
keepAlive = true;
lastKeepAlive = new Date();
client._keepAliveTimer = setInterval(keepAliveLoop, checkTimeoutInterval);
keepAliveTimer = setInterval(keepAliveLoop, checkTimeoutInterval);
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 {
'online-mode' : onlineMode = true,
kickTimeout = 30 * 1000,
keepAlive : enableKeepAlive = true,
errorHandler : clientErrorHandler=(client,err) => client.end(),
} = options;
@ -18,13 +17,9 @@ module.exports=function(client,server,options) {
client.on('error', function(err) {
clientErrorHandler(client, err);
});
client.on('end', onEnd);
function onEnd() {
clearInterval(client._keepAliveTimer);
client.on('end', () => {
clearTimeout(loginKickTimer);
}
});
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.state = states.PLAY;
loggedIn = true;
if(enableKeepAlive) client._startKeepAlive();
clearTimeout(loginKickTimer);
loginKickTimer = null;