I'm trying to receive a string from a device using this code:
byte[] buf = new byte[4];
int read = inFromDevice.read(buf);
Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Bytes read: {0}", read);
int msgLength = ByteBuffer.wrap(buf).getInt();
Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Message length: {0}", msgLength);
Reader r = new InputStreamReader(inFromDevice);
char[] cb = new char[msgLength];
int actualCharsRead = r.read(cb);
Logger.getLogger(Utill.class.getName() + " DEBUG_ERR01").log(Level.INFO, "Actual chars read: {0} char array length: {1}", new Object[]{actualCharsRead, cb.length});
String msgText = String.valueOf(cb, 0, cb.length);
Logger.getLogger(Utill.class.getName() + "Messages Loggining recieve: ").log(Level.INFO, msgText);
return msgText;
the inFromDevice is and InputStream acquired from an accepted ServerSocket.
The code is working and returning messages most of the time, but some times I get messages smaller than msgLength (which is wrong according to the protocol)
An example from the log is Actual chars read: 1020 char array length: 1391
I think the problem is external due to a network problem or device is having an issue, but I need some expert insight on this. are there any known problems in Java that may cause this?