Answer the question
In order to leave comments, you need to log in
How to read data from a socket?
Good afternoon. I have a slightly specific API that returns an array of bytes that needs to be parsed as an array of data or as a string. If I accept an array with a large size, for example 6000, then from 3000 there are only zeros in the following positions of the array. Through debug, the strangest thing is, everything is fine, if you put a breakpoint above the if condition - everything is fine. And if you put the breakpoint already lower, then from 3000 there are only zeros in the following positions of the array. Please help me figure out what's wrong.
private String receive() throws NullPointerException, IOException {
int lengthHeader = 19;
byte[] answerHeader = new byte[lengthHeader];
in.read(answerHeader);
byte[] bytesLength = Arrays.copyOfRange(answerHeader, 15, lengthHeader);
int lengthBody = bitConverterToInt32(bytesLength);
byte[] answer = new byte[lengthBody];
in.read(answer);
if (answer[0] == 0) {// строка
return new String(Arrays.copyOfRange(answer, 5, answer.length), Charset.forName(CHARSET_UTF16LE));
} else {//массив
StringBuilder builder = new StringBuilder();
byte[] lengthCommand = Arrays.copyOfRange(answer, 1, 2);
byte[] bytesRows = Arrays.copyOfRange(answer, 5, 6);
int maxRows = bytesRows[0];
int currentPos = lengthCommand[0] + 5 + 4;
for (int i = 0; i < maxRows; i++) {
byte[] bytes = Arrays.copyOfRange(answer, currentPos, currentPos + 4);
int rowLength = bitConverterToInt32(bytes);
currentPos += 4;
String splitter = i == 0 ? "" : "|";
builder.append(splitter);
byte[] bytes1 = Arrays.copyOfRange(answer, currentPos, currentPos + rowLength);
String s = new String(bytes1, Charset.forName(CHARSET_UTF16LE));
builder.append(splitter);
builder.append(s);
currentPos += rowLength;
}
return builder.toString();
}
}
Answer the question
In order to leave comments, you need to log in
in.read(answerHeader) - returns the number of bytes read, do not bet on the fact that it will always be read as much as you expect (more often it will be the other way around).
don't ignore idea warnings :)
if you want to block until you get the right amount of bytes then use readNBytes (since java 11).
// read to EOF which may read more or less than buffer size
while ((n = read(buf, nread, Math.min(buf.length - nread, remaining))) > 0) {
nread += n;
remaining -= n;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question