public BitTorrentMessage receiveMessage () throws IOException {
        try {
            // Message length
            inputBuffer.clear().limit(4);
            while (inputBuffer.remaining() > 0) {
                channel.read(inputBuffer);
            }
            inputBuffer.flip();
            int length = inputBuffer.getInt();

            // Message itself
            inputBuffer.clear().limit(length);
            while (inputBuffer.remaining() > 0) {
                channel.read(inputBuffer);
            }
            inputBuffer.flip();
            return BitTorrentMessageDecoder.decodeMessageFromBuffer(inputBuffer, length);
        } catch (IOException e) {
            // Channel error
            close();
            throw e;
        }
    }