I have an Android App that talks with a Java Server between socket connection. When server is running, there's no problem. I send something from Android and server answer. I get response and put it in Toast. Looks great! But if i stop running server, Android stay waiting for answer and all application stop working. Strange is the fact that application in running inside a thread, so i think its not supposed to happen. I'd like to know if is there some way to avoid it to crash application and some way to say to app's user that server doesn't respond. I'm sorry if is there some silly mistake, i'm just new in Java. The code:
public void onClick(DialogInterface dialog, int whichButton) {
InetAddress ia;
try {
ia = InetAddress.getByName("192.168.3.101");
s = new Socket(ia,12346);
Thread t = new Thread(new doComms(s));
t.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
And the class doComms:
class doComms implements Runnable {
private Socket s;
String line,inp;
doComms(Socket server) {
this.s=server;
}
public void run () {
inp="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (s.getInputStream());
PrintStream out = new PrintStream(s.getOutputStream());
out.println(input.getText().toString()+"\n.");
while((line = in.readLine()) != null && !line.equals(".")) {
inp=inp + line;
}
runOnUiThread(new Runnable() {
public void run() {
if(inp.equals("ok")){
Toast.makeText(Inicio.this,"Mensagem enviada com sucesso",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Inicio.this,"Falha ao enviar mensagem",Toast.LENGTH_LONG).show();
}
}
});
Log.v("inp", inp);
Log.v("type",inp.getClass().toString());
s.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}