I am interfacing with a network device and must read a response after I issue a command. Sometimes when I attempt to read, nothing has been returned from the terminal. This means I must wait, but not forever, right?
My solution: Enter a loop with a time comparison guard (time elapsed since start). Then inside, I will check to see if there is anything available to read. If so read it and break of the loop if nothing left.
I couldn't figure out another approach. Having a while
loop on the number of bytes read was fine up to the point where there was no data left, in which case it would just wait until the timeout to occur. My way will return as soon as everything has bead read or else timeout occurs.
Does this make sense? I currently have the timeout set to 10 seconds.
private Socket socket;
private DataInputStream reader;
private DataOutputStream writer;
socket = new Socket(device.getHostAddress(), device.getHostPort());
socket.setSoTimeout((int) READ_TIMEOUT_MILLIS);
reader = new DataInputStream(socket.getInputStream());
writer = new DataOutputStream(socket.getOutputStream());
writer.write(data.getBytes(ENCODING_CHARSET));
writer.flush();
ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
long opStartMillis = System.currentTimeMillis();
while(System.currentTimeMillis() - opStartMillis < READ_TIMEOUT_MILLIS) {
if(reader.available() > 0) {
int bytesRead = reader.read(buffer);
bufferStream.write(buffer, 0, bytesRead);
if(reader.available() == 0) {
break;
}
}
}
callback.dataReceived(bufferStream.toString(ENCODING_CHARSET));