KeepAliveTask requires keep alive interval <50% of server idle time

This started out at what seemed like a intermittent client disconnects and could not figure out why.

I setup the openfire server to have a xmpp.client.idle = 60000 (1 minute) and the client (smack) to send keep alives at the rate of 45 seconds. I think this should be a reasonally setting so the client will never be disconnected. I could just set the xmpp.client.idle = -1, but then if you have an unexpected disconnect (i.e. network down), then the server never knows the connection has gone…even worst if you have the xmpp.component.idle = -1, which means you have to restart the server to clean out stall connections.

Problem with the above setting is that if for example 40 seconds have elasped before the KeepAliveTask checks whether it needs to send a keep alive message, it won’t as the keep alive interval (45s) has not yet elasped. However at this point, it will wait the fully interval before retesting. However by that time the server client idle time has timed out and therefore will disconnect this client. I’m sure this shouldn’t be the intended behaviour.

I think the wait after each test should be based on how many seconds have already elapsed, so

long x = System.currentTimeMillis() - lastActive;
if (x >= delay) {
try {
writer.write(" ");
writer.flush();
}
catch (Exception e) {
}
}

try {
// Sleep until we should write the next keep-alive.
Thread.sleep(delay - x);
}
catch (InterruptedException ie) {
// Do nothing
}