Here is a way out to perform it which worked for me, it may be a little tricky and yes the code here is a combination of several answers which I found on StackOverflow.
The trick I used is to close the socket, make it NULL and then recreate and try to connect it.
It helps to clear the buffer and reconnect in a smooth way.
ackMessageTimeOut = new AckMessageTimeOut(5000) {
@Override
public void call(Object... args) {
if (args != null) {
if (args[0].toString().equalsIgnoreCase("No Ack")) {
Log.d("ACK_SOCKET", "AckWithTimeOut : " + args[0].toString());
acknowledgeMessage(null);
if (socket != null) {
socket.close();
socket = null;
connectSocket(); // Custom method which creates the socket and tries to connect it.
}
} else if (args[0].toString().equalsIgnoreCase("true")) {
cancelTimer(); //cancel timer if emit ACK return true
Log.d("ACK_SOCKET", "AckWithTimeOut : " + args[0].toString());
}
}
}
};
socket.emit("sendMessage", message, ackMessageTimeOut); // You can apply it on whatever event you want.
AckMessageTimeOut class is as below:
private class AckMessageTimeOut implements Ack {
private Timer timer;
private long timeOut = 0;
private boolean called = false;
AckMessageTimeOut(long timeout_after) {
if (timeout_after <= 0)
return;
this.timeOut = timeout_after;
startTimer();
}
private void startTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
callback("No Ack");
}
}, timeOut);
}
private void resetTimer() {
if (timer != null) {
timer.cancel();
startTimer();
}
}
void cancelTimer() {
if (timer != null)
timer.cancel();
}
void callback(Object... args) {
if (called)
return;
called = true;
cancelTimer();
call(args);
}
@Override
public void call(Object... objects) {
}
}