在做asmack的时候,发现有重连机制,分析了一下。
1、设置重连属性
ConnectionConfiguration.setReconnectionAllowed(boolean isAllowed)
public void setReconnectionAllowed(boolean isAllowed) {
this.reconnectionAllowed = isAllowed;
设置属性后,再调用这个方法是,查看是否重连
public boolean isReconnectionAllowed() {
return this.reconnectionAllowed;
}
2、在什么时候重连
connectionClosedOnError
parsePackets(Thread thread)
protected void reconnect() {
if (this.isReconnectionAllowed()) {
// Since there is no thread running, creates a new one to attempt
// the reconnection.
Thread reconnectionThread = new Thread() {
/**
* Holds the current number of reconnection attempts
*/
private int attempts = 0;
/**
* Returns the number of seconds until the next reconnection attempt.
*这个地方值得学习啊
* @return the number of seconds until the next reconnection attempt.
*/
private int timeDelay() {
if (attempts > 13) {
return 60 * 5; // 5 minutes
}
if (attempts > 7) {
return 60; // 1 minute
}
return 10; // 10 seconds
}
/**
* The process will try the reconnection until the connection succeed or the user
* cancell it
*/
public void run() {
// The process will try to reconnect until the connection is established or
// the user cancel the reconnection process {@link Connection#disconnect()}
while (ReconnectionManager.this.isReconnectionAllowed()) {
// Find how much time we should wait until the next reconnection
int remainingSeconds = timeDelay();
// Sleep until we're ready for the next reconnection attempt. Notify
// listeners once per second about how much time remains before the next
// reconnection attempt.
while (ReconnectionManager.this.isReconnectionAllowed() &&
remainingSeconds > 0)
{
try {
Thread.sleep(1000);
remainingSeconds--;
ReconnectionManager.this
.notifyAttemptToReconnectIn(remainingSeconds);
}
catch (InterruptedException e1) {
e1.printStackTrace();
// Notify the reconnection has failed
ReconnectionManager.this.notifyReconnectionFailed(e1);
}
}
// Makes a reconnection attempt
try {
if (ReconnectionManager.this.isReconnectionAllowed()) {
connection.connect();
}
}
catch (XMPPException e) {
// Fires the failed reconnection notification
ReconnectionManager.this.notifyReconnectionFailed(e);
}
}
}
};
reconnectionThread.setName("Smack Reconnection Manager");
reconnectionThread.setDaemon(true);
reconnectionThread.start();
}
}