I try to connect with my server by using socket on android. I want it to work like this; when i send a request to the server, if there is a response, call my response function. If the timeout of 500 ms happens (will check the exception and the boolean i set), i want to execute another function. But with this code im using, when i send something to the server and wait for response, it executes the onServerResponse function if there is a response and doesnt do anything(hangs) when there is not a response. How can i edit this code so it will throw a timeout exception when there is no response?
boolean control = false;
try{
Socket socket = new Socket();
socket.setSoTimeout(500);
socket.connect(new InetSocketAddress(InetAddress.getByName(SERVER_IP),SERVER_PORT));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
bw.write("asdasd\n");
bw.flush();
control = true;
int readInt = -1;
String read = null;
StringBuilder sb = new StringBuilder("");
while((readInt = socket.getInputStream().read()) != -1){
sb.append((char)readInt);
}
read = sb.toString();
if(read != null && read.trim().length() > 0){ onServerResponse(read); }
}catch(Exception e){ Log.v("Main", "GOT AN ERROR: "+e+control); }
Problem solved, see the comments for answer.
read()blocks for more than 500ms it will throw an exception. It's likely the connection attempt is what is blocking.