title: NIO blocking write not working
body: <p>I have recently been writing a Java NIO based server with non-blocking sockets and I've bumped in to some problems in regarding writing the data out. I know by now that there are conditions where non-blocking write fails to write some, or all of the bytes in a ByteBuffer. </p>
  
  <p>The way I currently handle such scenario is by either rewinding or compacting the buffer and later trying to send it again in next selection iteration. This how ever results in significant performance loss and it is imperative that I get the data sent fast.</p>
  
  <p>I have attempted using something like: </p>
  
  <pre><code>ByteBuffer bb = ...;
  SocketChannel sc = ...;
  while(bb.remaining() &gt; 0) { 
   sc.write(bb); 
  } 
  </code></pre>
  
  <p>But the problem with this is the fact that it might write 0 bytes and still quit the while loop. I'm not sure why, but it seems like write() - method will hit ByteBuffer's limit regardless of whether it actually sent all the bytes or not.</p>
  
  <p>Another problem I've had with this writing method is when it sometimes under heavy load will cause a buffer overflow exception even when I'm not attempting a blocking write.</p>
  
  <p>I desperately need some advice on how to properly perform blocking write and what condition might cause SocketChannel.write(ByteBuffer) to overflow the buffer(should it not stop when limit is hit?).</p>
  
  <p>Thanks in advance.</p>
  
  <p>Edit: I still have not found the reason why sc.write(bb) would set position in buffer to bb.limit() even if it wrote 0 bytes. My only resort remain to be rewinding the buffer after failed write attempt.</p>