## Prerequisites

This tutorial builds on the [FIDL server](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/server) tutorial. For the
full set of FIDL tutorials, refer to the [overview](https://fuchsia.dev/docs/development/languages/fidl/tutorials/overview).

## Overview

This tutorial implements a client for a FIDL protocol and runs it against the
server created in the [previous tutorial](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/server). The client in this
tutorial is asynchronous. There is an [alternate tutorial](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/sync-client) for
synchronous clients.

## Structure of the client example

The example code accompanying this tutorial is located in your Fuchsia checkout
at [`//examples/fidl/cpp/client`](https://cs.opensource.google/fuchsia/fuchsia/+/main:/examples/fidl/cpp/client). It consists of a client
component and its containing package. For more information about building
components, see [Build components](https://fuchsia.dev/docs/development/components/build).

To get the client component up and running, there are three targets that are
defined in `//examples/fidl/cpp/client/BUILD.bazel`:

1. The raw executable file for the client. This produces a binary with the
   specified output name that can run on Fuchsia:

   ```python
   fx_cc_binary(
       name = "bin",
       srcs = ["main.cc"],
       gn_output_name = "fidl_echo_cpp_client",
       tags = ["manual"],
       deps = [
           "//examples/fidl/fuchsia.examples:fuchsia.examples_cpp",

           # This library provides an asynchronous event loop implementation.
           "//sdk/lib/async-loop:async-loop-cpp",

           # This library is used to consume capabilities, e.g. protocols,
           # from the component's incoming directory.
           "//sdk/lib/component/incoming/cpp",

           # This library is used to log messages.
           "//sdk/lib/syslog/cpp",
       ],
   )

   ```
2. A component that is set up to run the client executable.
   Components are the units of software execution on Fuchsia. A component is
   described by its manifest file. In this case `meta/client.cml`
   configures `echo-client` as an executable component which runs
   `fidl_echo_cpp_client` in `:bin`.

   ```python
   fx_component_manifest(
       name = "echo-client_manifest",
       component_name = "echo_client",
       includes = ["//sdk/lib/syslog:client.shard"],
       manifest = "meta/client.cml",
   )

   fx_component(
       name = "echo-client",
       compiled_manifest = ":echo-client_manifest",
       visibility = [
           "//examples/fidl/cpp/server_async_completer:__pkg__",
           "//examples/fidl/echo-realm:__pkg__",
       ],
       deps = [":bin_packaged"],
   )
   ```

   The server component manifest is located at
   `//examples/fidl/cpp/client/meta/client.cml`. The binary name in the
   manifest must match the output name of the `executable` defined in
   `BUILD.bazel`.

   ```json5
   {
       include: [ "syslog/client.shard.cml" ],

       // Information about the program to run.
       program: {
           // Use the built-in ELF runner.
           runner: "elf",

           // The binary to run for this component.
           binary: "bin/fidl_echo_cpp_client",
       },

       // Capabilities used by this component.
       use: [
           { protocol: "fuchsia.examples.Echo" },
       ],
   }

   ```
3. The component is then put into a package, which is the unit of software
   distribution on Fuchsia. In this case, the package contains a client and
   a server component, and a


   [](https://fuchsia.dev/docs/glossary#realm)


   component to declare the
   appropriate capabilities and routes.

   ```python
   # C++ async client and server example package
   fx_package(
       name = "echo-cpp-client",
       components = [
           ":echo-client",
           "//examples/fidl/cpp/server:echo-server",
           "//examples/fidl/echo-realm:echo_realm",
       ],
       visibility = ["//examples/fidl/cpp:__pkg__"],
   )
   ```

### Building the client

1. Add the client to your build configuration. This only needs to be done once:

   ```bash
   fx set core.x64 --with //examples/fidl/cpp/client
   ```
2. Build the client:

   ```bash
   fx build examples/fidl/cpp/client
   ```

> [!NOTE]
> **Note:** This build configuration assumes your device target is the emulator. To run the example on a physical device, select the appropriate [product configuration](https://fuchsia.dev/docs/development/build/software_assembly/build_configuration) for your hardware.

## Connect to the protocol

In its main function, the client component connects to the
`fuchsia.examples/Echo` protocol in its


[](https://fuchsia.dev/docs/glossary#namespace)


.

```c++
int main(int argc, const char** argv) {
  // Connect to the |fuchsia.examples/Echo| protocol inside the component's
  // namespace. This can fail so it's wrapped in a |zx::result| and it must be
  // checked for errors.
  zx::result client_end = component::Connect<fuchsia_examples::Echo>();
  if (!client_end.is_ok()) {
    FX_LOGS(ERROR) << "Synchronous error when connecting to the |Echo| protocol: "
                   << client_end.status_string();
    return -1;
  }

  // ...
```

> [!NOTE]
> **Note:** There may still be asynchronous errors that causes peer of `client_end` to be closed, because the [open](https://fuchsia.dev/reference/fidl/fuchsia.io.md.txt#Directory.Open) operation uses [protocol request pipelining](https://fuchsia.dev/docs/development/api/fidl#request-pipelining): a pattern of making a request to connect the server end of the channel to an implementation, then immediately beginning to use the client endpoint. This topic is covered further in a separate [tutorial](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/topics/request-pipelining).

In parallel, the component manager will route the request to the server
component. The [server handler](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/server#server-handler) implemented in the server
tutorial will be called with the server endpoint, binding the channel to the
server implementation.

An important point to note here is that this code assumes that the component's
namespace already contains an instance of the `Echo` protocol. When
[running the example](https://fuchsia.dev/fuchsia-src/development/languages/fidl/tutorials/cpp/basics/client.md.txt#run-the-client) at the end of the tutorial, a


[](https://fuchsia.dev/docs/glossary#realm)


component is used to route the protocol from the server
and offer it to the client component.

## Initialize the event loop

An asynchronous client needs an `async_dispatcher_t*` to asynchronously monitor
messages from a channel. The `async::Loop` provides a dispatcher implementation
backed by an event loop.

```c++
  // As in the server, the code sets up an async loop so that the client can
  // listen for incoming responses from the server without blocking.
  async::Loop loop(&kAsyncLoopConfigNeverAttachToThread);
  async_dispatcher_t* dispatcher = loop.dispatcher();
```

The dispatcher is used to run pieces of asynchronous code. It is first used to
run the `EchoString` method, and quits when the response is received. It is then
run after calling the `SendString` in order to listen for events, and quits when
an `OnString` event is received. The call to `ResetQuit()` in between these two
instances allows the client to reuse the loop.

## Initialize the client

In order to make `Echo` requests to the server, initialize a client using the
client endpoint from the previous step, the loop dispatcher, as well as an event
handler delegate:

```c++
  // Define the event handler implementation for the client.
  //
  // The event handler delegate should be an object that implements the
  // |fidl::AsyncEventHandler<Echo>| virtual class, which has methods
  // corresponding to the events offered by the protocol. By default those
  // methods are no-ops.
  class EventHandler : public fidl::AsyncEventHandler<fuchsia_examples::Echo> {
   public:
    void OnString(fidl::Event<::fuchsia_examples::Echo::OnString>& event) override {
      FX_LOGS(INFO) << "(Natural types) got event: " << event.response();
      loop_.Quit();
    }

    // One may also override the |on_fidl_error| method, which is called
    // when the client encounters an error and is going to teardown.
    void on_fidl_error(fidl::UnbindInfo error) override { FX_LOGS(ERROR) << error; }

    explicit EventHandler(async::Loop& loop) : loop_(loop) {}

   private:
    async::Loop& loop_;
  };

  // Create an instance of the event handler.
  EventHandler event_handler{loop};

  // Create a client to the Echo protocol, passing our |event_handler| created
  // earlier. The |event_handler| must live for at least as long as the
  // |client|. The |client| holds a reference to the |event_handler| so it is a
  // bug for the |event_handler| to be destroyed before the |client|.
  fidl::Client client(std::move(*client_end), dispatcher, &event_handler);
```

## Make FIDL calls

The methods to make FIDL calls are exposed behind a dereference operator, such
that FIDL calls look like `client->EchoString(...)`.

An asynchronous `EchoString` call takes a request object, and accepts a callback
which is invoked with the result of the call, indicating success or failure:

```c++
  client->EchoString({"hello"}).ThenExactlyOnce(
      [&](fidl::Result<fuchsia_examples::Echo::EchoString>& result) {
        // Check if the FIDL call succeeded or not.
        if (!result.is_ok()) {
          // If the call failed, log the error, and crash the program.
          // Production code should do more graceful error handling depending
          // on the situation.
          FX_LOGS(ERROR) << "EchoString failed: " << result.error_value();
          ZX_PANIC("%s", result.error_value().FormatDescription().c_str());
        }
        // Dereference (->) the result object to access the response payload.
        FX_LOGS(INFO) << "(Natural types) got response: " << result->response();
        loop.Quit();
      });
  // Run the dispatch loop, until we receive a reply, in which case the callback
  // above will quit the loop, breaking us out of the |Run| function.
  loop.Run();
  loop.ResetQuit();
```

You may also use the designated initialization style double braces syntax
supported by [natural structs](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#natural_structs) and [tables](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#natural_tables):

```c++
  client->EchoString({{.value = "hello"}})
      .ThenExactlyOnce(
        // ... callback ...
```

A one way `SendString` call doesn't have a reply, so callbacks are not needed.
The returned result represents any errors occurred when sending the request.

```c++
  // Make a SendString one way call with natural types.
  fit::result<::fidl::Error> result = client->SendString({"hello"});
  if (!result.is_ok()) {
    FX_LOGS(ERROR) << "SendString failed: " << result.error_value();
    ZX_PANIC("%s", result.error_value().FormatDescription().c_str());
  }
```

### Make calls using wire domain objects

The above tutorial makes client calls with
[natural domain objects](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#using-natural): each call consumes request messages
represented using natural domain objects, and returns back replies also in
natural domain objects. When optimizing for performance and heap allocation, one
may make calls using [wire domain objects](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#using-wire). To do that, insert a
`.wire()` before the dereference operator used when making calls, i.e.
`client.wire()->EchoString(...)`.

Make a `EchoString` two way call with wire types:

```c++
  client.wire()->EchoString("hello").ThenExactlyOnce(
      [&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
        if (!result.ok()) {
          FX_LOGS(ERROR) << "EchoString failed: " << result.error();
          ZX_PANIC("%s", result.error().FormatDescription().c_str());
          return;
        }
        fidl::WireResponse<fuchsia_examples::Echo::EchoString>& response = result.value();
        std::string reply(response.response.data(), response.response.size());
        FX_LOGS(INFO) << "(Wire types) got response: " << reply;
        loop.Quit();
      });
```

Make a `SendString` one way call with wire types:

```c++
  fidl::Status wire_status = client.wire()->SendString("hello");
  if (!wire_status.ok()) {
    FX_LOGS(ERROR) << "SendString failed: " << result.error_value();
    ZX_PANIC("%s", result.error_value().FormatDescription().c_str());
  }
```

The relevant classes and functions used in a wire client call have similar
shapes to those used in a natural client call. When a different class or
function is called for, the wire counterpart is usually prefixed with `Wire`.
There are also differences in pointers vs references and argument structure:

- The `EchoString` method taking natural domain objects accepts a single
  argument that is the request domain object:

  ```c++
  client->EchoString({{.value = "hello"}})
      .ThenExactlyOnce(
  ```

  When the request payload is a struct, the `EchoString` method taking wire
  domain objects flattens the list of struct fields in the request body into
  separate arguments (here, a single `fidl::StringView` argument):

  ```c++
  client.wire()->EchoString("hello").ThenExactlyOnce(
  ```
- The callback in async natural calls accepts a `fidl::Result<Method>&`:

  ```c++
  client->EchoString({"hello"}).ThenExactlyOnce(
  \[\&\](fidl::Result\<fuchsia_examples::Echo::EchoString\>\& result) {
        // Check if the FIDL call succeeded or not.
        if (!result.is_ok()) {
          // If the call failed, log the error, and crash the program.
          // Production code should do more graceful error handling depending
          // on the situation.
          FX_LOGS(ERROR) << "EchoString failed: " << result.error_value();
          ZX_PANIC("%s", result.error_value().FormatDescription().c_str());
        }
        // Dereference (->) the result object to access the response payload.
        FX_LOGS(INFO) << "(Natural types) got response: " << result->response();
        loop.Quit();
      });
  // Run the dispatch loop, until we receive a reply, in which case the callback
  // above will quit the loop, breaking us out of the |Run| function.
  loop.Run();
  loop.ResetQuit();
  ```
  - To check for success or error, use the `is_ok()` or `is_error()` method.
  - To access the response payload afterwards, use `value()` or `->`.
  - You may move out the result or the payload since these types all implement hierarchical object ownership.

  The callback in async wire calls accepts a `fidl::WireUnownedResult<Method>&`:

  ```c++
  client.wire()->EchoString("hello").ThenExactlyOnce(
  \[\&\](fidl::WireUnownedResult\<fuchsia_examples::Echo::EchoString\>\& result) {
        if (!result.ok()) {
          FX_LOGS(ERROR) << "EchoString failed: " << result.error();
          ZX_PANIC("%s", result.error().FormatDescription().c_str());
          return;
        }
        fidl::WireResponse<fuchsia_examples::Echo::EchoString>& response = result.value();
        std::string reply(response.response.data(), response.response.size());
        FX_LOGS(INFO) << "(Wire types) got response: " << reply;
        loop.Quit();
      });
  ```
  - To check for success, use the `ok()` method.
  - To access the response payload afterwards, use `value()` or `->`.
  - You must synchronously use the result within the callback. The result type is *unowned*, meaning it only borrows the response allocated somewhere else by the FIDL runtime.
- One way calls also take the whole request domain object in the natural case,
  and flatten request struct fields into separate arguments in the wire case:

  ```c++
  // Make a SendString one way call with natural types.
  fit::result<::fidl::Error> result = client->SendString({"hello"});

  fidl::Status wire_status = client.wire()->SendString("hello");
  ```

## Run the client

In order for the client and server to communicate using the `Echo` protocol,
component framework must route the `fuchsia.examples.Echo` capability from the
server to the client. For this tutorial, a


[](https://fuchsia.dev/docs/glossary#realm)


component is
provided to declare the appropriate capabilities and routes.

> [!NOTE]
> **Note:** You can explore the full source for the realm component at [`//examples/fidl/echo-realm`](https://cs.opensource.google/fuchsia/fuchsia/+/main:/examples/fidl/echo-realm)

1. Configure your build to include the provided package that includes the
   echo realm, server, and client:

   ```bash
   fx set core.x64 --with //examples/fidl/cpp/client
   ```
2. Build the Fuchsia image:

   ```bash
   fx build
   ```
3. Run the `echo_realm` component. This creates the client and server component
   instances and routes the capabilities:

   ```bash
   ffx component run /core/ffx-laboratory:echo-realm fuchsia-pkg://fuchsia.com/echo-cpp-client#meta/echo_realm.cm
   ```
4. Start the `echo_client` instance:

   ```bash
   ffx component start /core/ffx-laboratory:echo-realm/echo_client
   ```

The server component starts when the client attempts to connect to the `Echo`
protocol. You should see output similar to the following in the device logs
(`ffx log`):

    [echo_server][][I] Running C++ echo server with natural types
    [echo_server][][I] Incoming connection for fuchsia.examples.Echo
    [echo_client][][I] (Natural types) got response: hello
    [echo_client][][I] (Natural types) got response: hello
    [echo_client][][I] (Natural types) got response: hello
    [echo_client][][I] (Natural types) got event: hello
    [echo_client][][I] (Wire types) got response: hello
    [echo_client][][I] (Natural types) got event: hello
    [echo_server][][I] Client disconnected

Terminate the realm component to stop execution and clean up the component
instances:

```bash
ffx component destroy /core/ffx-laboratory:echo_realm
```

## Wire domain objects only client

`fidl::Client` supports making calls with both
[natural domain objects](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#using-natural) and [wire domain objects](https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/domain-objects#using-wire).
If you only need to use wire domain objects, you may create a `WireClient` that
exposes the equivalent method call interface as the subset obtained from calling
`client.wire()` on a `fidl::Client`.

A `WireClient` is created the same way as a `Client`:

```c++
fidl::WireClient client(std::move(*client_end), dispatcher, &event_handler);
```

`fidl::Client` always exposes received events to the user in the form of natural
domain objects. On the other hand, `fidl::WireClient` will expose received
events in the form of wire domain objects. To do that, the event handler passed
to a `WireClient` needs to implement `fidl::WireAsyncEventHandler<Protocol>`.

- Implementing a natural event handler:

  ```c++
  class EventHandler : public fidl::AsyncEventHandler<fuchsia_examples::Echo> {
   public:
    void OnString(fidl::Event<::fuchsia_examples::Echo::OnString>& event) override {
      FX_LOGS(INFO) << "(Natural types) got event: " << event.response();
      loop_.Quit();
    }

    // ...
  };
  ```
- Implementing a wire event handler:

  ```c++
  class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
   public:
    void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
      FX_LOGS(INFO) << "(Natural types) got event: " << event->response.get();
      loop_.Quit();
    }

    // ...
  };
  ```

### Synchronous call

`WireClient` objects also allows synchronous calls, which will block until the
response is received and return the response object. These may be selected
using the `.sync()` accessor. (e.g. `client.sync()->EchoString()`).

```c++
  // Make a synchronous EchoString call, which blocks until it receives the response,
  // then returns a WireResult object for the response.
  fidl::WireResult result_sync = client.sync()->EchoString("hello");
  ZX_ASSERT(result_sync.ok());
  std::string_view response = result_sync->response.get();
  FX_LOGS(INFO) << "Got synchronous response: " << response;
```

In synchronous calls, a [result object](https://fuchsia.dev/docs/reference/fidl/bindings/cpp-bindings#resultof) is returned, synchronously
communicating the success or failure of the call.

The full example code for using a wire client is located in your Fuchsia
checkout at [`//examples/fidl/cpp/client/wire`](https://cs.opensource.google/fuchsia/fuchsia/+/main:/examples/fidl/cpp/client/wire).
[](https://issues.fuchsia.dev/issues/new?component=1439230&template=1881640&description=Issue+on:+https://fuchsia.dev/docs/development/languages/fidl/tutorials/cpp/basics/client.md "Report a bug or suggest improvements on this page") [](https://cs.opensource.google/fuchsia/fuchsia/+/main:docs/development/languages/fidl/tutorials/cpp/basics/client.md "View the source code of this page") [](https://ci.android.com/edit?repo=fuchsia/fuchsia/main&file=docs/development/languages/fidl/tutorials/cpp/basics/client.md&cloneRepo=fuchsia/fuchsia:refs/heads/main&fullPath=fuchsia/docs/development/languages/fidl/tutorials/cpp/basics/client.md "Edit the source code of this page")