Implement a 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.

If you want to write the code yourself, delete the following directories:

rm -r examples/fidl/hlcpp/client_sync/*

Create the component

Create a new component project at examples/fidl/hlcpp/client_sync:

  1. Add a main() function to examples/fidl/hlcpp/client_sync/main.cc:

    int main(int argc, const char** argv) {
      printf("Hello, world!\n");
      return 0;
    }
    
  2. Declare a target for the client in examples/fidl/hlcpp/client_sync/BUILD.gn:

    import("//build/components.gni")
    
    
    # Declare an executable for the client.
    executable("bin") {
      output_name = "fidl_echo_hlcpp_client_sync"
      sources = [ "main.cc" ]
    }
    
    fuchsia_component("echo-client") {
      component_name = "echo_client"
      manifest = "meta/client.cml"
      deps = [ ":bin" ]
    }
    
  3. Add a component manifest in examples/fidl/hlcpp/client_sync/meta/client.cml:

    {
        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_hlcpp_client_sync",
        },
    
        // Capabilities used by this component.
        use: [
            { protocol: "fuchsia.examples.Echo" },
        ],
    }
    
    
  4. Once you have created your component, ensure that you can add it to the build configuration:

    fx set core.x64 --with //examples/fidl/hlcpp/client_sync:echo-client
  5. Build the Fuchsia image:

    fx build

Edit GN dependencies

  1. Add the following dependencies:

      deps = [
        "//examples/fidl/fuchsia.examples:fuchsia.examples_hlcpp",
        "//sdk/lib/sys/cpp",
      ]
    
    
  2. Then, include them in main.cc:

    #include <fuchsia/examples/cpp/fidl.h>
    #include <lib/sys/cpp/component_context.h>
    

    The reason for including these dependencies is explained in the server tutorial.

Connect to the server

This section adds code the main() function that connects to the server and makes requests to it.

Initialize a proxy class

The code then creates a proxy class for the Echo protocol, and connects it to the server. In the context of FIDL, proxy designates the code generated by the FIDL bindings that enables users to make remote procedure calls to the server. In HLCPP, the proxy takes the form of a class with methods corresponding to each FIDL protocol method.

int main(int argc, const char** argv) {
  fuchsia::examples::EchoSyncPtr echo_proxy;
  auto context = sys::ComponentContext::Create();
  context->svc()->Connect(echo_proxy.NewRequest());

  ZX_ASSERT(echo_proxy->SendString("hi") == ZX_OK);
  std::string response;
  ZX_ASSERT(echo_proxy->EchoString("hello", &response) == ZX_OK);
  printf("Got response: %s\n", response.c_str());

  // TODO(fcz): this currently does not pass on CQ
  // return response == "hello" ? 0 : 1;
  return 0;
}
  • fuchsia::examples::EchoSyncPtr is an alias for fidl::SynchronousInterfaceRequest<fuchsia::examples::Echo> generated by the bindings. This class will proxy requests for the Echo protocol over the channel that it is bound to.
  • The code calls EchoSyncPtr::NewRequest(), which will create a channel, bind the class to one end, and return the other end
  • The returned end is passed to sys::ServiceDirectory::Connect().
    • Analogous to the call to context->out()->AddPublicService() on the server side, Connect has an implicit second parameter here, which is the protocol name ("fuchsia.examples.Echo"). This is where the input to the handler defined in the previous tutorial comes from: the client passes it in to Connect, which then passes it to the handler.

An important point to note here is that this code assumes that /svc already contains an instance of the Echo protocol. This is not the case by default because of the sandboxing provided by the component framework.

Send requests to the server

The code makes two requests to the server:

  • An EchoString request
  • A SendString request
int main(int argc, const char** argv) {
  fuchsia::examples::EchoSyncPtr echo_proxy;
  auto context = sys::ComponentContext::Create();
  context->svc()->Connect(echo_proxy.NewRequest());

  ZX_ASSERT(echo_proxy->SendString("hi") == ZX_OK);
  std::string response;
  ZX_ASSERT(echo_proxy->EchoString("hello", &response) == ZX_OK);
  printf("Got response: %s\n", response.c_str());

  // TODO(fcz): this currently does not pass on CQ
  // return response == "hello" ? 0 : 1;
  return 0;
}

For EchoString the code passes in a pointer for each response parameter (in this case, the EchoString method only has one response parameter), which is written with the response from the server, whereas this does not apply to SendString since it is a fire and forget method. The call to EchoString will block until it receives a message from the server. Both methods will return a zx_status_t indicating the result of the method call.

Though the server implementation sends an OnString event in response to the SendString request, the sync bindings do not provide a way to handle this event.

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/hlcpp:echo-hlcpp-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_realm fuchsia-pkg://fuchsia.com/echo-hlcpp-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

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

ffx component destroy /core/ffx-laboratory:echo_realm