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

Implement a sync 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 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/llcpp/client_sync/*

Create the component

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

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

    int main(int argc, const char** argv) {
      std::cout << "Hello, world!" << std::endl;
    }
    
  2. Declare a target for the client in examples/fidl/llcpp/client_sync/BUILD.gn:

    import("//build/components.gni")
    
    
    # Declare an executable for the client.
    executable("bin") {
      output_name = "fidl_echo_llcpp_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/llcpp/client_sync/meta/client.cml:

    {
        include: [
            "syslog/client.shard.cml",
            "syslog/elf_stdio.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_llcpp_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.qemu-x64 --with //examples/fidl/llcpp/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_llcpp",
        "//sdk/lib/fdio",
        "//zircon/system/ulib/service:service-llcpp",
      ]
    
    
  2. Then, include them in main.cc:

    #include <fidl/fuchsia.examples/cpp/wire.h>
    #include <lib/service/llcpp/service.h>
    #include <zircon/assert.h>
    
    #include <iostream>
    

These dependencies are explained in the server tutorial. The client requires far fewer dependencies because it does not need to run any asynchronous code.

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.

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) {
  // |service::OpenServiceRoot| returns a channel connected to the /svc directory.
  // The remote end of the channel implements the |fuchsia.io/Directory| protocol
  // and contains the capabilities provided to this component.
  auto svc = service::OpenServiceRoot();
  ZX_ASSERT(svc.is_ok());

  // Connect to the fuchsia.examples.Echo protocol.
  auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
  ZX_ASSERT(client_end.is_ok());

  // Create a synchronous-only client to the Echo protocol.
  auto client = fidl::BindSyncClient(std::move(*client_end));

  {
    // Make an EchoString request, then print out the response.
    auto result = client.EchoString("hello");
    ZX_ASSERT(result.ok());
    std::string reply_string(result->response.data(), result->response.size());
    std::cout << "Got response: " << reply_string << std::endl;
  }

  {
    // Make a SendString request
    auto result = client.SendString("hi");
    // Check that the request was sent successfully.
    ZX_ASSERT(result.ok());

    class EventHandler : public fidl::WireSyncEventHandler<fuchsia_examples::Echo> {
     public:
      EventHandler() = default;

      void OnString(fidl::WireResponse<fuchsia_examples::Echo::OnString>* event) override {
        std::string reply_string(event->response.data(), event->response.size());
        std::cout << "Got event: " << reply_string << std::endl;
      }

      zx_status_t Unknown() override { return ZX_ERR_NOT_SUPPORTED; }
    };

    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    EventHandler event_handler;
    ZX_ASSERT(client.HandleOneEvent(event_handler).ok());
  }

  return 0;
}

The service::OpenServiceRoot function initializes a channel, then passes the server end to fdio_service_connect to connect to the /svc directory, returning the client end wrapped in a zx::status result type. We should check for the is_ok() value on the result to determine if any synchronous error occurred.

Connecting to a protocol relative to the service directory 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. The service::ConnectAt function wraps the low level fdio call, providing the user with a typed client channel endpoint to the requested protocol.

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.

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) {
  // |service::OpenServiceRoot| returns a channel connected to the /svc directory.
  // The remote end of the channel implements the |fuchsia.io/Directory| protocol
  // and contains the capabilities provided to this component.
  auto svc = service::OpenServiceRoot();
  ZX_ASSERT(svc.is_ok());

  // Connect to the fuchsia.examples.Echo protocol.
  auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
  ZX_ASSERT(client_end.is_ok());

  // Create a synchronous-only client to the Echo protocol.
  auto client = fidl::BindSyncClient(std::move(*client_end));

  {
    // Make an EchoString request, then print out the response.
    auto result = client.EchoString("hello");
    ZX_ASSERT(result.ok());
    std::string reply_string(result->response.data(), result->response.size());
    std::cout << "Got response: " << reply_string << std::endl;
  }

  {
    // Make a SendString request
    auto result = client.SendString("hi");
    // Check that the request was sent successfully.
    ZX_ASSERT(result.ok());

    class EventHandler : public fidl::WireSyncEventHandler<fuchsia_examples::Echo> {
     public:
      EventHandler() = default;

      void OnString(fidl::WireResponse<fuchsia_examples::Echo::OnString>* event) override {
        std::string reply_string(event->response.data(), event->response.size());
        std::cout << "Got event: " << reply_string << std::endl;
      }

      zx_status_t Unknown() override { return ZX_ERR_NOT_SUPPORTED; }
    };

    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    EventHandler event_handler;
    ZX_ASSERT(client.HandleOneEvent(event_handler).ok());
  }

  return 0;
}

The protocol methods on the client object (EchoString and SendString) return a result object, which will contain either an error or the contents of the response (if any). When a response is expected, the client will block until the response is received.

A client object is generated for each protocol, which is described further in the LLCPP bindings reference.

Handle events

The client object allows handling events by specifying an event delegate, where each method corresponds to one of the events of the protocol, plus a Unknown handler for when an unknown event is received.

The code defines a handler, which prints the contents of an OnString event, then calls client.HandleOneEvent() to block until an event is received. If an unknown event is received, its return value becomes the return value of the HandleOneEvent call:

int main(int argc, const char** argv) {
  // |service::OpenServiceRoot| returns a channel connected to the /svc directory.
  // The remote end of the channel implements the |fuchsia.io/Directory| protocol
  // and contains the capabilities provided to this component.
  auto svc = service::OpenServiceRoot();
  ZX_ASSERT(svc.is_ok());

  // Connect to the fuchsia.examples.Echo protocol.
  auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
  ZX_ASSERT(client_end.is_ok());

  // Create a synchronous-only client to the Echo protocol.
  auto client = fidl::BindSyncClient(std::move(*client_end));

  {
    // Make an EchoString request, then print out the response.
    auto result = client.EchoString("hello");
    ZX_ASSERT(result.ok());
    std::string reply_string(result->response.data(), result->response.size());
    std::cout << "Got response: " << reply_string << std::endl;
  }

  {
    // Make a SendString request
    auto result = client.SendString("hi");
    // Check that the request was sent successfully.
    ZX_ASSERT(result.ok());

    class EventHandler : public fidl::WireSyncEventHandler<fuchsia_examples::Echo> {
     public:
      EventHandler() = default;

      void OnString(fidl::WireResponse<fuchsia_examples::Echo::OnString>* event) override {
        std::string reply_string(event->response.data(), event->response.size());
        std::cout << "Got event: " << reply_string << std::endl;
      }

      zx_status_t Unknown() override { return ZX_ERR_NOT_SUPPORTED; }
    };

    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    EventHandler event_handler;
    ZX_ASSERT(client.HandleOneEvent(event_handler).ok());
  }

  return 0;
}

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.qemu-x64 --with //examples/fidl/llcpp:echo-llcpp-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 fuchsia-pkg://fuchsia.com/echo-llcpp-client-sync#meta/echo_realm.cm
    
  4. Start the echo_client instance:

    ffx component bind /core/ffx-laboratory:echo_realm/echo_client
    

The server component starts when the client attempts to connect to the Echo protocol. You should see the following output using fx log:

[echo_server] INFO: Running echo server
[echo_server] INFO: Incoming connection for fuchsia.examples.Echo
[echo_client] INFO: Got response: hello
[echo_client] INFO: Got event: hi

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

ffx component destroy /core/ffx-laboratory:echo_realm