def recv_nbytes(sock, n_bytes):
    """Receive exactly `n_bytes`.
    If the connection is closed, `None` will be returned.

    Args:
        sock (socket.socket): An socket object.
        n_bytes (int): Amount of data to receive.

    Returns:
        bytes: Received data.
    """
    ret = bytes()
    while len(ret) < n_bytes:
        part = sock.recv(min(4096, n_bytes - len(ret)))
        if part == '':
            return None  # the connection is closed
        ret += part
    return ret