Implement a synchronous C++ FIDL client

Prerequisites

This tutorial builds on the FIDL server tutorial. For the full set of FIDL tutorials, refer to the overview.

Overview

This tutorial implements a client for a FIDL protocol and runs it against the server created in the previous tutorial. The client in this tutorial is synchronous. There is an alternate tutorial for asynchronous clients.

Structure of the client example

The example code accompanying this tutorial is located in your Fuchsia checkout at //examples/fidl/cpp/client_sync. It consists of a client component and its containing package. For more information about building components, see Build components.

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

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

    executable("bin") {
      output_name = "fidl_echo_cpp_client_sync"
      sources = [ "main.cc" ]
    
      deps = [
        "//examples/fidl/fuchsia.examples:fuchsia.examples_cpp",
    
        # This library is used to log messages.
        "//sdk/lib/syslog/cpp",
    
        # This library is used to consume capabilities, e.g. protocols,
        # from the component's incoming directory.
        "//sdk/lib/component/incoming/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_sync in :bin.

    fuchsia_component("echo-client") {
      component_name = "echo_client"
      manifest = "meta/client.cml"
      deps = [ ":bin" ]
    }
    
    

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

    {
        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_sync",
        },
    
        // 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 realm component to to declare the appropriate capabilities and routes.

    # C++ sync client and server example package
    fuchsia_package("echo-cpp-client-sync") {
      deps = [
        ":echo-client",
        "//examples/fidl/cpp/server:echo-server",
        "//examples/fidl/echo-realm:echo_realm",
      ]
    }
    
    

Building the client

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

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

    fx build examples/fidl/cpp/client_sync
    

Connect to the protocol

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

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;
  }

  // ...

In parallel, the component manager will route the request to the server component. The 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 at the end of the tutorial, a realm component is used to route the protocol from the server and offer it to the client component.

Initialize the client

In order to make Echo requests to the server, initialize a client using the client endpoint from the previous step.

fidl::SyncClient client{std::move(*client_end)};

Make FIDL calls

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

A two way call such as EchoString takes a request object, and returns a result object indicating success or failure:

fidl::Result result = client->EchoString({"hello"});
// Check if the FIDL call succeeded or not.
if (!result.is_ok()) {
  // If the call failed, log the error, and quit the program.
  // Production code should do more graceful error handling depending
  // on the situation.
  FX_LOGS(ERROR) << "EchoString failed: " << result.error_value();
  return -1;
}
const std::string& reply_string = result->response();
FX_LOGS(INFO) << "Got response: " << reply_string;

You may also use the designated initialization style double braces syntax supported by natural structs and tables:

fidl::Result result = client->EchoString({{.value = "hello"}});

A one way SendString call doesn't have a reply. The returned result represents any errors that occurred when sending the request.

fit::result<fidl::Error> result = client->SendString({"hi"});
if (!result.is_ok()) {
  FX_LOGS(ERROR) << "SendString failed: " << result.error_value();
  return -1;
}

Handle events

Define an event handler:

// Define the event handler implementation for the client.
//
// The event handler should be an object that implements
// |fidl::SyncEventHandler<Echo>|, and override all pure virtual methods
// in that class corresponding to the events offered by the protocol.
class EventHandler : public fidl::SyncEventHandler<fuchsia_examples::Echo> {
 public:
  EventHandler() = default;

  void OnString(fidl::Event<fuchsia_examples::Echo::OnString>& event) override {
    const std::string& reply_string = event.response();
    FX_LOGS(INFO) << "Got event: " << reply_string;
  }
};

Call client.HandleOneEvent to block until an event is received. If the event was recognized and successfully decoded, HandleOneEvent returns fidl::Status::Ok(). Otherwise, it returns an appropriate error. If the server closes the connection with an epitaph, the status contained in the epitaph is returned.

// Block to receive exactly one event from the server, which is handled using
// the event handler defined above.
EventHandler event_handler;
fidl::Status status = client.HandleOneEvent(event_handler);
if (!status.ok()) {
  FX_LOGS(ERROR) << "HandleOneEvent failed: " << status.error();
  return -1;
}

Make calls using wire domain objects

The above tutorial makes client calls with natural domain objects: 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. 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:

fidl::WireResult result = client.wire()->EchoString("hello");
if (!result.ok()) {
  FX_LOGS(ERROR) << "EchoString failed: " << result.error();
  return -1;
}
FX_LOGS(INFO) << "Got response: " << result->response.get();

Make a SendString one way call with wire types:

fidl::Status wire_result = client.wire()->SendString("hi");
if (!wire_result.ok()) {
  FX_LOGS(ERROR) << "SendString failed: " << wire_result.error();
  return -1;
}

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:

    fidl::Result result = client->EchoString({{.value = "hello"}});
    

    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):

    fidl::WireResult result = client.wire()->EchoString("hello");
    
  • The two way natural calls return a fidl::Result<Method>:

    fidl::Result result = client->EchoString({{.value = "hello"}});
    if (!result.is_ok()) {
      FX_LOGS(ERROR) << "EchoString failed: " << result.error_value();
      return -1;
    }
    const std::string& reply_string = result->response();
    FX_LOGS(INFO) << "Got response: " << reply_string;
    
    • 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 two way wire calls return a fidl::WireResult<Method>:

    fidl::WireResult result = client.wire()->EchoString("hello");
    if (!result.ok()) {
      FX_LOGS(ERROR) << "EchoString failed: " << result.error();
      return -1;
    }
    FX_LOGS(INFO) << "Got response: " << result->response.get();
    
    • To check for success, use the ok() method.
    • To access the response payload afterwards, use value() or ->.
    • You cannot move the result object.
  • 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:

    // Make a SendString call using natural types.
    fit::result<fidl::Error> result = client->SendString({"hi"});
    
    // Make a SendString call using wire types.
    fidl::Status wire_result = client.wire()->SendString("hi");
    

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 realm component is provided to declare the appropriate capabilities and routes.

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

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

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

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

    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 echo server
[echo_client][I] Got response: hello
[echo_client][I] Got event: hi
[echo_client][I] Got response: hello
[echo_server][I] Client disconnected

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

ffx component destroy /core/ffx-laboratory:echo_realm

Wire domain objects only client

fidl::SyncClient supports making calls with both natural domain objects and wire domain objects. If you only need to use wire domain objects, you may create a WireSyncClient that exposes the equivalent method call interface as the subset obtained from calling client.wire() on a fidl::SyncClient.

A WireSyncClient is created the same way as a SyncClient:

fidl::WireSyncClient client(std::move(*client_end));

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

  • Implementing a natural event handler:

    // Define the event handler implementation for the client.
    //
    // The event handler should be an object that implements
    // |fidl::SyncEventHandler<Echo>|, and override all pure virtual methods
    // in that class corresponding to the events offered by the protocol.
    class EventHandler : public fidl::SyncEventHandler<fuchsia_examples::Echo> {
     public:
      EventHandler() = default;
    
      void OnString(fidl::Event<fuchsia_examples::Echo::OnString>& event) override {
        const std::string& reply_string = event.response();
        FX_LOGS(INFO) << "Got event: " << reply_string;
      }
    };
    
  • Implementing a wire event handler:

    // Define the event handler implementation for the client.
    //
    // The event handler should be an object that implements
    // |fidl::WireSyncEventHandler<Echo>|, and override all pure virtual methods
    // in that class corresponding to the events offered by the protocol.
    class EventHandler : public fidl::WireSyncEventHandler<fuchsia_examples::Echo> {
     public:
      EventHandler() = default;
    
      void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
        FX_LOGS(INFO) << "Got event: " << event->response.get();
      }
    };
    

The full example code for using a wire client is located in your Fuchsia checkout at //examples/fidl/cpp/client_sync/wire.