I'm trying to get all the data from a SocketChannel into a ByteBuffer. Since I may be getting different length messages from the channel, I'd like to loop until a read returns me 0 bytes, in which case I know I'm done and that all data is now in the buffer. I'm aware I need to also handle the case of a -1 returned from a read.
ByteBuffer buf = ByteBuffer.allocate(maxBytes);
int bytesRead;
while ((bytesRead = channel.read(buf)) > 0) {
totalBytesRead += bytesRead;
}
return totalBytesRead;
When I run this code, however, it reads the full data on the first read, but then when it reads for the second time (and I expect 0 bytes), something goes wrong and it breaks. What's strange is that I get no error messages, and when stepping through in debug mode, it doesn't go to the next line, i.e. the return.