def recv_exactly(recv_fn, size):
recv_bytes = <NUM_LIT:0><EOL>chunks = []<EOL>while recv_bytes < size:<EOL><INDENT>chunk = recv_fn(size - recv_bytes)<EOL>if len(chunk) == <NUM_LIT:0>:  <EOL><INDENT>break<EOL><DEDENT>recv_bytes += len(chunk)<EOL>chunks.append(chunk)<EOL><DEDENT>response = b'<STR_LIT>'.join(chunks)<EOL>if len(response) != size:<EOL><INDENT>raise ValueError<EOL><DEDENT>return response<EOL>
Use the function to read and return exactly number of bytes desired.

    https://docs.python.org/3/howto/sockets.html#socket-programming-howto for
    more information about why this is necessary.

    :param recv_fn: Function that can return up to given bytes
        (i.e. socket.recv, file.read)
    :param size: Number of bytes to read.
    :return: Byte string with length size.
    :raises ValueError: Could not receive enough data (usually timeout).