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

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

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

rm -r examples/fidl/llcpp/client/*

Create a stub component

  1. Set up a hello world component in examples/fidl/llcpp/client. You can name the component echo-client, and give the package a name of echo-llcpp-client.

  2. Once you have created your component, ensure that the following works:

    fx set core.x64 --with //examples/fidl/llcpp/client
    
  3. Build the Fuchsia image:

    fx build
    
  4. In a separate terminal, run:

    fx serve
    
  5. In a separate terminal, run:

    fx shell run fuchsia-pkg://fuchsia.com/echo-llcpp-client#meta/echo-client.cmx
    

Edit GN dependencies

  1. Add the following dependencies:

      deps = [
        "//examples/fidl/fuchsia.examples:fuchsia.examples_llcpp",
        "//sdk/lib/fdio",
        "//zircon/public/lib/fidl",
        "//zircon/system/ulib/async-loop:async-loop-cpp",
        "//zircon/system/ulib/async-loop:async-loop-default",
      ]
    
    
  2. Then, include them in main.cc:

    #include <fuchsia/examples/llcpp/fidl.h>
    #include <lib/async-loop/cpp/loop.h>
    #include <lib/async-loop/default.h>
    #include <lib/fdio/directory.h>
    #include <lib/fidl/llcpp/client.h>
    #include <lib/zx/channel.h>
    #include <zircon/status.h>
    
    #include <iostream>
    

These dependencies are explained in the server tutorial.

Edit component manifest

  1. Include the Echo protocol in the client component's sandbox by editing the component manifest in client.cmx.

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

Connect to the server

The steps in this section explain how to add code to the main() function that connects the client to the server and makes requests to it.

Initialize the event loop

As in the server, the code first sets up an async loop so that the client can listen for incoming responses from the server without blocking.

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

  auto svc = get_svc_directory();
  zx::channel server_end, client_end;
  ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
  // Connect to the fuchsia.examples.Echo protocol.
  ZX_ASSERT(fdio_service_connect_at(svc.get(), "fuchsia.examples.Echo", server_end.release()) ==
            ZX_OK);

  // Define the event handlers for the client. The OnString event handler prints the event
  llcpp::fuchsia::examples::Echo::AsyncEventHandlers handlers = {
      .on_string = [&](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
        std::string event(message->response.data(), message->response.size());
        std::cout << "Got event: " << event << std::endl;
        loop.Quit();
      }};
  // Create a client to the Echo protocol
  fidl::Client<llcpp::fuchsia::examples::Echo> client(std::move(client_end), dispatcher,
                                                      std::move(handlers));

  // Make an EchoString call, passing it a lambda to handle the response asynchronously.
  client->EchoString("hello", [&](fidl::StringView resp) {
    std::string reply(resp.data(), resp.size());
    std::cout << "Got response: " << reply << std::endl;
    loop.Quit();
  });
  loop.Run();
  loop.ResetQuit();

  // Make a synchronous EchoString call, which blocks until it receives the response,
  // then returns a ResultOf object for the response.
  auto result = client->EchoString_Sync("hello");
  ZX_ASSERT(result.ok());
  std::string reply_string(result->response.data(), result->response.size());
  std::cout << "Got synchronous response: " << reply_string << std::endl;

  // Make a SendString request. The resulting OnString event will be handled by
  // the event handler defined above.
  client->SendString("hi");
  loop.Run();

  return 0;
}

The dispatcher is used to run two pieces of async 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.

Connect to the server

The client then connects to the service directory /svc, and uses it to connect to the server.

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

  auto svc = get_svc_directory();
  zx::channel server_end, client_end;
  ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
  // Connect to the fuchsia.examples.Echo protocol.
  ZX_ASSERT(fdio_service_connect_at(svc.get(), "fuchsia.examples.Echo", server_end.release()) ==
            ZX_OK);

  // Define the event handlers for the client. The OnString event handler prints the event
  llcpp::fuchsia::examples::Echo::AsyncEventHandlers handlers = {
      .on_string = [&](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
        std::string event(message->response.data(), message->response.size());
        std::cout << "Got event: " << event << std::endl;
        loop.Quit();
      }};
  // Create a client to the Echo protocol
  fidl::Client<llcpp::fuchsia::examples::Echo> client(std::move(client_end), dispatcher,
                                                      std::move(handlers));

  // Make an EchoString call, passing it a lambda to handle the response asynchronously.
  client->EchoString("hello", [&](fidl::StringView resp) {
    std::string reply(resp.data(), resp.size());
    std::cout << "Got response: " << reply << std::endl;
    loop.Quit();
  });
  loop.Run();
  loop.ResetQuit();

  // Make a synchronous EchoString call, which blocks until it receives the response,
  // then returns a ResultOf object for the response.
  auto result = client->EchoString_Sync("hello");
  ZX_ASSERT(result.ok());
  std::string reply_string(result->response.data(), result->response.size());
  std::cout << "Got synchronous response: " << reply_string << std::endl;

  // Make a SendString request. The resulting OnString event will be handled by
  // the event handler defined above.
  client->SendString("hi");
  loop.Run();

  return 0;
}

In practice, this is done by calling fdio_service_connect_at, passing it the service directory, the name of the service to connect to, as well as the channel that should get passed to the server. In parallel, the component manager will route the requested service name and channel to the server component, where the connect function implemented in the server tutorial is called with these arguments, binding the channel to the server implementation.

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. A workaround will be when running the example at the end of the tutorial.

The get_svc_directory() function is defined as follows:

// Returns a channel connected to the /svc directory. The
// remote end of the channel implements the io.Directory protocol and contains
// the capabilities provided to this component.
zx::channel get_svc_directory() {
  zx::channel server_end, client_end;
  ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
  ZX_ASSERT(fdio_service_connect("/svc/.", server_end.release()) == ZX_OK);
  return client_end;
}

Similar to the fdio_service_connect_at call above, this function initializes a channel, and passes the server end to fdio_service_connect to connect to the /svc directory, returning the client end.

Initialize the client

In order to make Echo requests to the server, initialize a client using the other end of the channel from the previous step, the loop dispatcher, as well as an event handler struct:

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

  auto svc = get_svc_directory();
  zx::channel server_end, client_end;
  ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
  // Connect to the fuchsia.examples.Echo protocol.
  ZX_ASSERT(fdio_service_connect_at(svc.get(), "fuchsia.examples.Echo", server_end.release()) ==
            ZX_OK);

  // Define the event handlers for the client. The OnString event handler prints the event
  llcpp::fuchsia::examples::Echo::AsyncEventHandlers handlers = {
      .on_string = [&](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
        std::string event(message->response.data(), message->response.size());
        std::cout << "Got event: " << event << std::endl;
        loop.Quit();
      }};
  // Create a client to the Echo protocol
  fidl::Client<llcpp::fuchsia::examples::Echo> client(std::move(client_end), dispatcher,
                                                      std::move(handlers));

  // Make an EchoString call, passing it a lambda to handle the response asynchronously.
  client->EchoString("hello", [&](fidl::StringView resp) {
    std::string reply(resp.data(), resp.size());
    std::cout << "Got response: " << reply << std::endl;
    loop.Quit();
  });
  loop.Run();
  loop.ResetQuit();

  // Make a synchronous EchoString call, which blocks until it receives the response,
  // then returns a ResultOf object for the response.
  auto result = client->EchoString_Sync("hello");
  ZX_ASSERT(result.ok());
  std::string reply_string(result->response.data(), result->response.size());
  std::cout << "Got synchronous response: " << reply_string << std::endl;

  // Make a SendString request. The resulting OnString event will be handled by
  // the event handler defined above.
  client->SendString("hi");
  loop.Run();

  return 0;
}

The event handlers should be a struct with fields corresponding to the events offered by the protocol (see LLCPP event handlers). In this case, a struct is defined with a single field corresponding to the handler for the OnString event. The handler prints the string and quits the event loop.

Send requests to the server

The code makes three requests to the server:

  • An asynchronous EchoString request.
  • A synchronous EchoString request.
  • A SendString request (async vs sync is not relevant for this case because it is a fire and forget method).
int main(int argc, const char** argv) {
  async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
  async_dispatcher_t* dispatcher = loop.dispatcher();

  auto svc = get_svc_directory();
  zx::channel server_end, client_end;
  ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
  // Connect to the fuchsia.examples.Echo protocol.
  ZX_ASSERT(fdio_service_connect_at(svc.get(), "fuchsia.examples.Echo", server_end.release()) ==
            ZX_OK);

  // Define the event handlers for the client. The OnString event handler prints the event
  llcpp::fuchsia::examples::Echo::AsyncEventHandlers handlers = {
      .on_string = [&](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
        std::string event(message->response.data(), message->response.size());
        std::cout << "Got event: " << event << std::endl;
        loop.Quit();
      }};
  // Create a client to the Echo protocol
  fidl::Client<llcpp::fuchsia::examples::Echo> client(std::move(client_end), dispatcher,
                                                      std::move(handlers));

  // Make an EchoString call, passing it a lambda to handle the response asynchronously.
  client->EchoString("hello", [&](fidl::StringView resp) {
    std::string reply(resp.data(), resp.size());
    std::cout << "Got response: " << reply << std::endl;
    loop.Quit();
  });
  loop.Run();
  loop.ResetQuit();

  // Make a synchronous EchoString call, which blocks until it receives the response,
  // then returns a ResultOf object for the response.
  auto result = client->EchoString_Sync("hello");
  ZX_ASSERT(result.ok());
  std::string reply_string(result->response.data(), result->response.size());
  std::cout << "Got synchronous response: " << reply_string << std::endl;

  // Make a SendString request. The resulting OnString event will be handled by
  // the event handler defined above.
  client->SendString("hi");
  loop.Run();

  return 0;
}

The client object works by overriding the dereference operator to return a protocol specific client implementation, allowing calls such as client->EchoString().

The asynchronous method call requires the request parameters followed by a response handler callback, which is called when the response is received.

The client object also allows synchronous calls, which will block until the response is received and return the response object. These are suffixed with _Sync (e.g. client->EchoString_Sync()).

In the synchronous case, a result object is returned, since the method call can fail. In the asynchronous case, the response handler callback takes as arguments the response parameters directly, since the handler is only called in the case of a successfull method call.

Run the client

If you run the client directly, it will not connect to the server correctly because the client does not automatically get the Echo protocol provided in its sandbox (in /svc). To get this to work, a launcher tool is provided that launches the server, creates a new Environment for the client that provides the server's protocol, then launches the client in it.

  1. Configure your GN build as follows:

    fx set core.x64 --with //examples/fidl/llcpp/server --with //examples/fidl/llcpp/client --with //examples/fidl/test:echo-launcher
    
  2. Build the Fuchsia image:

    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-llcpp-client#meta/echo-client.cmx fuchsia-pkg://fuchsia.com/echo-llcpp-server#meta/echo-server.cmx fuchsia.examples.Echo
    

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

[166633.167] 757796:757798> Running echo server
[166633.489] 757796:757798> echo_server_llcpp: Incoming connection for fuchsia.examples.Echo
[166633.528] 758101:758103> Got synchronous response: hello
[166633.531] 758101:758103> Got response: hello
[166633.531] 758101:758103> Got event: hi"