我正在尝试使用以下代码从设备接收字符串:
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;
inFromDevice是从接受的ServerSocket获取的InputStream。
代码大部分时间都在工作并返回消息,但有时我得到的消息小于msgLength (根据协议,这是错误的)
日志中的一个示例是Actual chars read: 1020 char array length: 1391
我认为问题是外部的,因为网络问题或设备有问题,但我需要一些专家的洞察力。Java中有没有什么已知的问题可能会导致这种情况?
https://stackoverflow.com/questions/55599976
复制相似问题