FIXED THE BUG!
The nature of Socket IO is that the sockets timeout (or in this case, DISCONNECTS) if there are no activities present in the socket. When your phone goes to idle mode (when it sleeps), there is no constant connection that checks whether the app is active or not. One simple way to keep the socket alive is to send constant heartbeats (or ping pongs) every 20-30 seconds or so!
Server-side:
io.sockets.on('connection', function (socket) {
socket.on('pong', function(data){
console.log("Pong received from client");
});
setTimeout(sendHeartbeat, 25000);
function sendHeartbeat(){
setTimeout(sendHeartbeat, 25000);
io.sockets.emit('ping', { beat : 1 });
}
});
Client-Side:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket.connect();
mSocket.on("ping", sendPong);
}
private Emitter.Listener sendPong = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String ping;
try {
ping = data.getString("ping");
} catch (JSONException e) {
return;
}
if(ping.equals("1")){
SocketSingleton.get(getApplicationContext()).getSocket().emit("pong", "pong");
}
Log.e("SOCKETPING", "RECEIVED PING! ");
}
});
}
};
This WILL work! And this does NOT drain battery! This is the BEST fix I have found so far!
In my experience, I do not think u need to establish a Singleton method if you have only ONE activity. You can open the connection in your main class, and turn on and off sockets in your fragment. And of course, turn off the sockets on onDestroy method in your fragment classes. I just used Singleton as a security to make sure I don't create multiple instances if Android somehow screws up.
So, here is my Singleton class:
public class SocketSingleton {
private static SocketSingleton instance;
private static final String SERVER_ADDRESS = "http://YOUR_ADDRESS:PORT/";
private Socket mSocket;
private Context context;
public SocketSingleton(Context context) {
this.context = context;
this.mSocket = getServerSocket();
}
public static SocketSingleton get(Context context){
if(instance == null){
instance = getSync(context);
}
instance.context = context;
return instance;
}
private static synchronized SocketSingleton getSync(Context context) {
if(instance == null){
instance = new SocketSingleton(context);
}
return instance;
}
public Socket getSocket(){
return this.mSocket;
}
public Socket getServerSocket() {
try {
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = true;
mSocket = IO.socket(SERVER_ADDRESS, opts);
return mSocket;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
And my MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SocketSingleton.get(this).getSocket().connect();
SocketSingleton.get(getApplicationContext()).getSocket().emit("joinSocket", SEND_USER_ID);
/// Send pongs to keep connection active;
SocketSingleton.get(this).getSocket().on("ping", sendPong);
SocketSingleton.get(this).getSocket().on(Socket.EVENT_RECONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
SocketSingleton.get(getApplicationContext()).getSocket().emit("joinSocket", SEND_USER_ID);
}
});
}
private Emitter.Listener sendPong = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String ping;
try {
ping = data.getString("ping");
} catch (JSONException e) {
return;
}
if(ping.equals("1")){
SocketSingleton.get(getApplicationContext()).getSocket().emit("pong", current_user);
}
ping_counter++;
Log.e("SOCKETPING", "RECEIVED PING: " + ping_counter);
TextView pingReceived = (TextView) findViewById(R.id.pingReceived);
try{
pingReceived.setText(ping_counter + "");
} catch (Exception e) {
}
}
});
}
};
Hope this helped you! also, if you make this code better, please do consider sharing. Thanks.