I'm writing a server that is supposed to communicate with some embedded devices. The communication protocol is based on a fixed length header. The problem is I can't get my server to handle sudden disconnects of the devices properly (by "sudden" I mean situations when I just turn the device off). Here is the code for the client thread main loop:
while(!terminate) {
try {
// Receive the header
while(totalBytesRead < ServerCommon.HEADER_SIZE) {
bytesRead = dis.read(headerBuffer, bytesRead, ServerCommon.HEADER_SIZE - bytesRead);
if(bytesRead == -1) {
// Can't get here!
}
else {
totalBytesRead += bytesRead;
}
}
totalBytesRead = 0;
bytesRead = 0;
type = Conversion.byteArrayToShortOrder(headerBuffer, 0);
length = Conversion.byteArrayToShortOrder(headerBuffer, 2);
// Receive the payload
while(totalBytesRead < length) {
bytesRead = dis.read(receiveBuffer, bytesRead, length - bytesRead);
if(bytesRead == -1) {
// Can't get here!
}
else {
totalBytesRead += bytesRead;
}
}
totalBytesRead = 0;
bytesRead = 0;
// Pass received frame to FrameDispatcher
Even if I turn the device off, the read method keeps returning 0, not -1. How this could be?