您好,我在 Android 中有一个带有 tcp 套接字连接的客户端服务器架构。我的服务“onStart()”中有一个套接字侦听器线程。我想在不知何故失去连接后重新连接到服务器。我该如何设计这个问题?我尝试了一些方法,但我在服务启动中陷入了无限循环......感谢您的回答。
监听器代码是这样的......
@Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onSTARTED!!");
if(!mySocket.isConnected()){
connectiontoServer();
}
clientListenerThread = new Thread(new Runnable() { // TCP Socket Listener
public void run() {
String line = new String();
try {
while(mySocket.isConnected() && ((line = in.readLine()) != null)){
try{
Log.d(TAG, "service onStart-while true");
String[] tokens = line.split(MessageClass.ayirac);
Log.d(TAG+"-MSG", line);
tokens = line.split(MessageClass.ayirac);
int msgCase = Integer.parseInt(tokens[0]);
switch(msgCase){
case -5:
responseEntrance(line);
break;
case 1:
responseLogin1(line);
break;
case 2:
responseRegister2(tokens);
break;
default:
break;
}
}catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "CATCH1 !");
continue;
}
}
}catch(IOException e){
e.printStackTrace();
if(!mySocket.isConnected()){
Log.d(TAG,"ConnectionDOWN! in catch2");
stopAndDestroyMyActivity();
}
}
Log.d(TAG, "LISTENING FINISH!");
stopAndDestroyMyActivity();
}
});
clientListenerThread.start();
}