@Override
  public void write(final byte[] b, final int off, final int len) throws IOException {
    if (anyAreSet(state, FLAG_CLOSED)) {
      throw UndertowServletMessages.MESSAGES.streamIsClosed();
    }
    if (listener == null) {
      Channels.writeBlocking(channel, ByteBuffer.wrap(b, off, len));
    } else {
      if (anyAreClear(state, FLAG_READY)) {
        throw UndertowServletMessages.MESSAGES.streamNotReady();
      }
      int res;
      ByteBuffer buffer = ByteBuffer.wrap(b);
      do {
        res = channel.write(buffer);
        if (res == 0) {

          ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
          copy.put(buffer);
          copy.flip();
          this.buffer = copy;
          state = state & ~FLAG_READY;
          channel.resumeWrites();
          return;
        }
      } while (buffer.hasRemaining());
    }
  }
 void closeBlocking() throws IOException {
   state |= FLAG_CLOSED;
   try {
     if (buffer != null) {
       Channels.writeBlocking(channel, buffer);
     }
     channel.shutdownWrites();
     Channels.flushBlocking(channel);
   } finally {
     channel.close();
   }
 }
 @Override
 public void sendBinary(final ByteBuffer partialByte, final boolean isLast) throws IOException {
   if (textFrameSender != null) {
     throw JsrWebSocketMessages.MESSAGES.cannotSendInMiddleOfFragmentedMessage();
   }
   if (binaryFrameSender == null) {
     binaryFrameSender = webSocketChannel.send(WebSocketFrameType.BINARY);
   }
   try {
     Channels.writeBlocking(binaryFrameSender, partialByte);
     if (isLast) {
       binaryFrameSender.shutdownWrites();
       Channels.flushBlocking(binaryFrameSender);
     }
   } finally {
     if (isLast) {
       binaryFrameSender = null;
     }
   }
 }
 @Override
 public void sendText(final String partialMessage, final boolean isLast) throws IOException {
   if (binaryFrameSender != null) {
     throw JsrWebSocketMessages.MESSAGES.cannotSendInMiddleOfFragmentedMessage();
   }
   if (textFrameSender == null) {
     textFrameSender = webSocketChannel.send(WebSocketFrameType.TEXT);
   }
   try {
     Channels.writeBlocking(textFrameSender, WebSocketUtils.fromUtf8String(partialMessage));
     if (isLast) {
       textFrameSender.shutdownWrites();
       Channels.flushBlocking(textFrameSender);
     }
   } finally {
     if (isLast) {
       textFrameSender = null;
     }
   }
 }