1

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.

  • is it in blocking or non-blocking mode? – Charlie Dec 01 '18 at 22:09
  • oh yeah - non-blocking mode – user9569574 Dec 01 '18 at 22:10
  • can you try to add a try {} catch (Exception ex) { /*print here something*/ } For example you can put it around the while loop. In the catch block you can add a breakpoint and read the ex variable. – Charlie Dec 01 '18 at 22:18
  • yep, I actually have a try catch around the while loop like you are suggesting. I set my breakpoint on the catch /*print*/, yet right after it calls the read the second time, it just does its own thing. Doesn't go to my next 'step' in the debugger, and isn't caught by the catch. – user9569574 Dec 01 '18 at 22:23
  • Do you have a minimal debuggable application you can share with us? – Charlie Dec 01 '18 at 22:37

0 Answers0