Google is committed to advancing racial equity for Black communities. See how.

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 will be asynchronous. There is an alternate tutorial for synchronous clients.

If you'd like to follow along and write the code yourself, feel free to delete the example code:

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

Create a stub component

Referring back to the previous tutorial as necessary, start by setting up a hello world component in examples/fidl/hlcpp/client. You can name the component echo-client, and give the package a name of echo-hlcpp-client. You should ensure that the following works:

fx set core.x64 --with //examples/fidl/hlcpp/client_sync
fx build
fx serve
fx shell run fuchsia-pkg://fuchsia.com/echo-hlcpp-client-sync#meta/echo-client.cmx

Edit GN dependencies

Next, add the following dependencies:

  deps = [
    "//examples/fidl/fuchsia.examples",
    "//sdk/lib/sys/cpp",
  ]

and include them in main.cc:

#include <fuchsia/examples/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/sys/cpp/component_context.h>

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

Edit component manifest

Finally, include the Echo protocol in the client component's sandbox by editing the component manifest in client.cmx.

{
    "program": {
        "binary": "bin/fidl_echo_hlcpp_client"
    },
    "sandbox": {
        "services": [
            "fuchsia.examples.Echo"
        ]
    }
}

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" is used to designate 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) {
  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);

  fuchsia::examples::EchoPtr echo_proxy;
  auto context = sys::ComponentContext::Create();
  context->svc()->Connect(echo_proxy.NewRequest());

  echo_proxy.set_error_handler([&loop](zx_status_t status) {
    printf("Error reading incoming message: %d\n", status);
    loop.Quit();
  });

  int num_responses = 0;
  echo_proxy->SendString("hi");
  echo_proxy->EchoString("hello", [&](std::string response) {
    printf("Got response %s\n", response.c_str());
    if (++num_responses == 2) {
      loop.Quit();
    }
  });
  echo_proxy.events().OnString = [&](std::string response) {
    printf("Got event %s\n", response.c_str());
    if (++num_responses == 2) {
      loop.Quit();
    }
  };

  loop.Run();
  return num_responses == 2 ? 0 : 1;
}
  • 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: one SendString request, and one EchoString request:

int main(int argc, const char** argv) {
  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);

  fuchsia::examples::EchoPtr echo_proxy;
  auto context = sys::ComponentContext::Create();
  context->svc()->Connect(echo_proxy.NewRequest());

  echo_proxy.set_error_handler([&loop](zx_status_t status) {
    printf("Error reading incoming message: %d\n", status);
    loop.Quit();
  });

  int num_responses = 0;
  echo_proxy->SendString("hi");
  echo_proxy->EchoString("hello", [&](std::string response) {
    printf("Got response %s\n", response.c_str());
    if (++num_responses == 2) {
      loop.Quit();
    }
  });
  echo_proxy.events().OnString = [&](std::string response) {
    printf("Got event %s\n", response.c_str());
    if (++num_responses == 2) {
      loop.Quit();
    }
  };

  loop.Run();
  return num_responses == 2 ? 0 : 1;
}

Notice that 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][one-way]. 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 will send an OnString event in response to the SendString request, the sync bindings do not provide a way to handle this event.

Check that this builds using fx build.

Run the client

If you try running the client directly, you'll notice that the error handler gets called because the client does not automatically get the Echo protocol provided in its sandbox (in /svc). In order to get this to work, a launcher tool is provided that will launch the server, create a new Environment for the client that provides the server's protocol, then launch the client in it.

  1. Configure your GN build as follows:

    fx set core.x64 --with //examples/fidl/hlcpp/server --with //examples/fidl/hlcpp/client --with //examples/fidl/test:echo-launcher

  2. Build

    fx build

  3. Run the launcher by passing it the client URL, the server URL, and the protocol that the server provides to the client:

    fx shell run fuchsia-pkg://fuchsia.com/echo-launcher#meta/launcher.cmx fuchsia-pkg://fuchsia.com/echo-hlcpp-client#meta/echo-client.cmx fuchsia-pkg://fuchsia.com/echo-hlcpp-server#meta/echo-server.cmx fuchsia.examples.Echo

You should see the client print output in the QEMU console (or using fx log).

[117942.207] 757245:757247> Running echo server
[117942.223] 757349:757352> Got response: hello