I am using the below code for my Server to continue listening to Client message once it's become connected.
While listening, I wanted to detect if the Client become disconnected when read
value becomes -1
and finished the WhileLoop
.
private volatile boolean isConnected = true;
//....
while(isConnected){ //Whe it comes to false then Receiving Message is Done.
try {
socket.setSoTimeout(10000); //Timeout is 10 Seconds
InputStream inputStream = socket.getInputStream();
BufferedInputStream inputS = new BufferedInputStream(inputStream);
byte[] buffer = new byte[256];
int read = inputS.read(buffer);
String msgData = new String(buffer,0,read);
//Detect here when client become disconnected
if(read == -1){ //Client become disconnected
isConnected = false;
Log.w(TAG,"Client is no longer Connected!");
}else{
isConnected = true;
Log.w(TAG,"Client Still Connected...");
}
//....
}catch (SocketException e) {
Log.e(TAG,"Failed to Receive message from Client, SocketException occured => " + e.toString());
}catch (IOException e) {
Log.e(TAG,"Failed to Receive message from Client, IOException occured => " + e.toString());
}catch (Exception e) {
Log.e(TAG,"Failed to Receive message from Client, Exception occured => " + e.toString());
}
}
Log.w(TAG, "Receiving Message is Done.");
The above code works on receiving message but I'm having problem detecting when the client become disconnected.
When the client become disconnected, an Exception is occured whith the following error: java.lang.StringIndexOutOfBoundsException: length=256; regionStart=0; regionLength=-1
and the WhileLoop
is not breaking as expected to be done.
I am assuming that when the client become disconnected then this condition will occured if(read == -1){....}
.
I just found this post while searching and the answer of EJP give me the best solution on read() returns -1
, but I'm just starting on ServerSocket
so I don't know if I'm doing it correctly.
String msgData = new String(buffer,0,read);
If read
is -1 it will throw an Exception. I'd totally expect that.
Just move that line to your else
branch where you check read for -1 so the string will only be constructed when there is actually data.
See: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-int-int-
Throws: IndexOutOfBoundsException - If the offset and the length arguments index characters outside the bounds of the bytes array
-1 length is outside of bounds :)