private void writeBuffer(long timeout, long startTime, ByteBuffer queryBuffer) throws IOException {
        SelectionKey writeKey = socketChannel.register(selector, SelectionKey.OP_WRITE);

        boolean firstTime = true;
        while (queryBuffer.hasRemaining() && currentTime() - startTime < timeout) {
            if (!firstTime) {
                long waitDuration = startTime + timeout - currentTime();
                if (waitDuration > 0) {
                    selector.select(waitDuration);
                }
            }

            if (firstTime || selector.selectedKeys().size() > 0) {
                int written;
                do {
                    written = socketChannel.write(queryBuffer);
                } while (written > 0);

                if (firstTime) {
                    firstTime = false;
                } else {
                    selector.selectedKeys().remove(writeKey);
                }
            }
        }
    }