private void blockForWrite() throws IOException {
        SelectionKey key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        while (!key.isWritable()) {
            int selected = selector.select();
            if (selected == 0) {
                throw new IOException("failed to select");
            }
            if (key.isReadable()) {
                drain();
            }
        }
    }