Commit 7ec3fdfd by Simhachalam ch

Added socket connection acknowledgement and ping events to resolve freeze issues

parent 8d1ba475
...@@ -174,7 +174,7 @@ public class CatalogueApplication extends MultiDexApplication { ...@@ -174,7 +174,7 @@ public class CatalogueApplication extends MultiDexApplication {
options.upgrade = true; options.upgrade = true;
mSocket = IO.socket(Constants.CHAT_SERVER_URL,options); mSocket = IO.socket(Constants.CHAT_SERVER_URL,options);
// mSocket = IO.socket("http://10.1.8.229:12811",options); // mSocket = IO.socket("http://74cb19e2.ngrok.io/",options);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
......
...@@ -116,6 +116,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -116,6 +116,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
private static final String TAG = ChatActivity.class.getName();//"ChatActivity"; private static final String TAG = ChatActivity.class.getName();//"ChatActivity";
private static String NEW_MESSAGE = "new message"; private static String NEW_MESSAGE = "new message";
private static String MESSAGE_DELIVERED = "messageDelivered";
private static String SERVER_PING_PONG = "server_ping_pong";
private static String AUTHENTICATED = "authenticated"; private static String AUTHENTICATED = "authenticated";
private static String UNAUTHORIZED = "unauthorized"; private static String UNAUTHORIZED = "unauthorized";
private static String ADD_USER = "add user"; private static String ADD_USER = "add user";
...@@ -169,6 +171,34 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -169,6 +171,34 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
private final static String INIT_MSG = "hi"; private final static String INIT_MSG = "hi";
private String chatHistroy= ""; private String chatHistroy= "";
String ChatHistorybase64; String ChatHistorybase64;
/**
* using this flag for implement client and server
* acknowledgement
*/
private boolean hasMsgSent = false;
private final int ACK_EVENT = 2;
private String clientMsg;
/**
* using this flag to check current
* socket id is valid or not
*
*/
private boolean hasPingPongPassed = false;
private boolean hasRequestProcessCompleted = false;
private final int PING_PONG_EVENT = 3;
/**
* 2O SECS for ideal acknowledgement
*/
private final int ACK_TIMEOUT = 15000;
/**
* 3O SECS for ideal acknowledgement
*/
private final int PING_PONG_TIMEOUT = 30000;
/** /**
* These var will to set delay for listing dialog. Previously it will open for infinite time. * These var will to set delay for listing dialog. Previously it will open for infinite time.
* Now open the listening, if user will not response it'll close after 10 Secs. * Now open the listening, if user will not response it'll close after 10 Secs.
...@@ -182,6 +212,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -182,6 +212,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
private LinearLayout mainLayt; private LinearLayout mainLayt;
private PowerManager.WakeLock wl; private PowerManager.WakeLock wl;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
...@@ -244,6 +275,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -244,6 +275,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
mSocket.on(NEW_MESSAGE, onNewMessage); mSocket.on(NEW_MESSAGE, onNewMessage);
mSocket.on(AUTHENTICATED, authenticated); mSocket.on(AUTHENTICATED, authenticated);
mSocket.on(UNAUTHORIZED, unAuthorized); mSocket.on(UNAUTHORIZED, unAuthorized);
mSocket.on(MESSAGE_DELIVERED, onMessageDelivered);
mSocket.on(SERVER_PING_PONG, onServerPingPongTest);
mSocket.connect(); mSocket.connect();
...@@ -277,6 +310,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -277,6 +310,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
e.printStackTrace(); e.printStackTrace();
} }
mSocket.emit(NEW_MESSAGE, jsonObject); mSocket.emit(NEW_MESSAGE, jsonObject);
hasMsgSent = false;
} }
...@@ -403,10 +437,81 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -403,10 +437,81 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
} }
private void readAndWriteCallsData() { /**
* Handling client-server acknowledgement
* to avoid chot bot freeze issues
*/
private Handler ackHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(!hasMsgSent || !hasPingPongPassed){
/**
* reset the socket connection
* if message is not reached with in 20 secs.
*/
if(mSocket.connected()){
//if it is connected then disconnect
Log.e(TAG, "socket is going to disconnect");
mSocket.disconnect();
}
ChatLogManager.saveLogEvent("Connection Broken - Message not sent to server","",String.valueOf(mSocket.connected()), mSocket.id(),new Date());
//recreat the socket connection here
mSocket.connect();
Log.e(TAG, "socket reconnecting...");
handlerDelayMessage.postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textDotLoader.hide();
mInputMessageView.setText(clientMsg);
showSocketConnectError(R.string.error_connect_try_again);
}
});
}
}, 1000);
}else{
Log.i(TAG, "message delivered successfully");
}
}
};
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.vsoft.vera/databases/db/"+DATABASE_NAME); /**
* Handling client-server ping pong test
* to avoid chot bot freeze issues
*/
private Handler pingPongHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mSocket.emit(SERVER_PING_PONG, "ping");
ChatLogManager.saveLogEvent("PING","",String.valueOf(mSocket.connected()), mSocket.id(),new Date());
waitForServerAcknowledgement();
Log.i(TAG, "send ping to server");
}
};
private void waitForServerAcknowledgement(){
Message msg = ackHandler.obtainMessage(ACK_EVENT);
ackHandler.sendMessageDelayed(msg, ACK_TIMEOUT);
}
private void startPingPongTest(){
hasPingPongPassed = false;
pingPongHandler.removeCallbacksAndMessages(null);
Message msg = pingPongHandler.obtainMessage(PING_PONG_EVENT);
pingPongHandler.sendMessageDelayed(msg, PING_PONG_TIMEOUT);
Log.i(TAG, "PING PONG TEST SCHEDULED");
}
private void readAndWriteCallsData() {
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.vsoft.vera/databases/db/"+ DATABASE_NAME);
try { try {
File path = getDatabasePath(DATABASE_NAME); File path = getDatabasePath(DATABASE_NAME);
...@@ -723,6 +828,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -723,6 +828,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
if (NetworkConnectivity.haveNetworkConnection(ChatActivity.this)) { if (NetworkConnectivity.haveNetworkConnection(ChatActivity.this)) {
String message = mInputMessageView.getText().toString().trim(); String message = mInputMessageView.getText().toString().trim();
clientMsg = message;
if (!TextUtils.isEmpty(message)){ if (!TextUtils.isEmpty(message)){
if (null == mLoggedInUsername) return; if (null == mLoggedInUsername) return;
...@@ -736,7 +842,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -736,7 +842,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
* then we are reconnecting and send the message again * then we are reconnecting and send the message again
*/ */
if (!mSocket.connected()){ if (!mSocket.connected()){
showSocketConnectError(); mSocket.disconnect();
showSocketConnectError(R.string.error_connect);
mSocket.connect(); mSocket.connect();
return; return;
} }
...@@ -762,6 +869,9 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -762,6 +869,9 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
Log.i("Print", jsonObject.toString()); Log.i("Print", jsonObject.toString());
mSocket.emit(NEW_MESSAGE, jsonObject); mSocket.emit(NEW_MESSAGE, jsonObject);
hasMsgSent = false;
hasRequestProcessCompleted = false;
waitForServerAcknowledgement();
ChatLogManager.saveLogEvent(message,"",String.valueOf(mSocket.connected()), mSocket.id(),new Date()); ChatLogManager.saveLogEvent(message,"",String.valueOf(mSocket.connected()), mSocket.id(),new Date());
} else { } else {
...@@ -803,7 +913,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -803,7 +913,7 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
@Override @Override
public void run() { public void run() {
// userAuthenticateTask(); // userAuthenticateTask();
Log.e(TAG, "socket got connected" + mSocket.id()); Log.e(TAG, "socket got connected - " + mSocket.id());
// Toast.makeText(getApplicationContext(), // Toast.makeText(getApplicationContext(),
// R.string.connect, Toast.LENGTH_LONG).show(); // R.string.connect, Toast.LENGTH_LONG).show();
initChatMessage(INIT_MSG); initChatMessage(INIT_MSG);
...@@ -835,17 +945,23 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -835,17 +945,23 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
clientMsg = message;
mSocket.emit(NEW_MESSAGE, jsonObject); mSocket.emit(NEW_MESSAGE, jsonObject);
hasMsgSent = false;
hasRequestProcessCompleted = false;
waitForServerAcknowledgement();
} }
} }
private void showSocketConnectError(){ private void showSocketConnectError(final int msgResourceId){
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
Log.e(TAG,"failed to connect"); handlerDelayMessage.removeCallbacksAndMessages(null);
Log.e(TAG,"connect error");
Snackbar snackbar = Snackbar Snackbar snackbar = Snackbar
.make(mMessagesView, R.string.error_connect, Snackbar.LENGTH_LONG) .make(mMessagesView, msgResourceId, Snackbar.LENGTH_LONG)
.setAction("Dismiss", new View.OnClickListener() { .setAction("Dismiss", new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
...@@ -943,8 +1059,17 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -943,8 +1059,17 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
@Override @Override
public void run() { public void run() {
if(!isConnectError) { if(!isConnectError) {
ackHandler.removeCallbacksAndMessages(null);
pingPongHandler.removeCallbacksAndMessages(null);
Log.e(TAG,"failed to connect"); Log.e(TAG,"failed to connect");
runOnUiThread(new Runnable() {
@Override
public void run() {
textDotLoader.hide();
}
});
Snackbar snackbar = Snackbar Snackbar snackbar = Snackbar
.make(mMessagesView, R.string.error_connect, Snackbar.LENGTH_LONG) .make(mMessagesView, R.string.error_connect, Snackbar.LENGTH_LONG)
.setAction("Dismiss", new View.OnClickListener() { .setAction("Dismiss", new View.OnClickListener() {
...@@ -991,6 +1116,11 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -991,6 +1116,11 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
private Emitter.Listener onNewMessage = new Emitter.Listener() { private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override @Override
public void call(final Object... args) { public void call(final Object... args) {
mSocket.emit(MESSAGE_DELIVERED,"message delivered to client");
hasRequestProcessCompleted = true;
ackHandler.removeCallbacksAndMessages(null);
pingPongHandler.removeCallbacksAndMessages(null);
Log.i(TAG, "PING PONG SCHEDULE DISMISSED");
/*Reset this flag every time*/ /*Reset this flag every time*/
mIsConversationEnd = false; mIsConversationEnd = false;
...@@ -1120,6 +1250,43 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -1120,6 +1250,43 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
} }
}; };
/**
* Chat server calls this method if user is unauthorized
*/
private Emitter.Listener onMessageDelivered = new Emitter.Listener() {
@Override
public void call(final Object... args) {
ackHandler.removeCallbacksAndMessages(null);
hasMsgSent = true;
String acknowledgement = (String) args[0];
CatalogueLog.i(acknowledgement);
ChatLogManager.saveLogEvent("","Message reached to server",String.valueOf(mSocket.connected()), mSocket.id(),new Date());
//start ping pong test here
startPingPongTest();
}
};
/**
* ping pong test for current session with server
*/
private Emitter.Listener onServerPingPongTest = new Emitter.Listener() {
@Override
public void call(final Object... args) {
hasPingPongPassed = true;
ackHandler.removeCallbacksAndMessages(null);
Log.i(TAG, "ping pong test passed");
String pingPongMsg = (String) args[0];
CatalogueLog.i(pingPongMsg);
ChatLogManager.saveLogEvent("",pingPongMsg,String.valueOf(mSocket.connected()), mSocket.id(),new Date());
//check if it has to reschedule or not continue the ping test
if(!hasRequestProcessCompleted){
startPingPongTest();
}
}
};
private void refreshTokenApiTask() { private void refreshTokenApiTask() {
CatalogueLog.d("-- is 401, try refresh token..."); CatalogueLog.d("-- is 401, try refresh token...");
CatalogueLog.d("refresh token: " + PrefManager.getSharedPref(this, PrefManager.PREFERENCE_REFRESH_TOKEN)); CatalogueLog.d("refresh token: " + PrefManager.getSharedPref(this, PrefManager.PREFERENCE_REFRESH_TOKEN));
...@@ -1495,6 +1662,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD ...@@ -1495,6 +1662,8 @@ public class ChatActivity extends AppCompatActivity implements OnDSListener, OnD
mSocket.off(NEW_MESSAGE, onNewMessage); mSocket.off(NEW_MESSAGE, onNewMessage);
mSocket.off(AUTHENTICATED, authenticated); mSocket.off(AUTHENTICATED, authenticated);
mSocket.off(UNAUTHORIZED, unAuthorized); mSocket.off(UNAUTHORIZED, unAuthorized);
mSocket.off(MESSAGE_DELIVERED, onMessageDelivered);
mSocket.off(SERVER_PING_PONG, onServerPingPongTest);
} }
wl.release(); wl.release();
......
...@@ -140,6 +140,7 @@ ...@@ -140,6 +140,7 @@
<string name="connect">Connected</string> <string name="connect">Connected</string>
<string name="disconnect">Disconnected, Please check your internet connection</string> <string name="disconnect">Disconnected, Please check your internet connection</string>
<string name="error_connect">Failed to connect</string> <string name="error_connect">Failed to connect</string>
<string name="error_connect_try_again">Failed to connect. Please try again!</string>
<string name="unauthorized_user">Unauthorized User</string> <string name="unauthorized_user">Unauthorized User</string>
<!-- messages --> <!-- messages -->
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment