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 a stub component

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

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

    fx set core.x64 --with //examples/fidl/llcpp/client_sync
    
  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-sync#meta/echo-client.cmx
    

Edit GN dependencies

  1. Add the following dependencies:

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

    #include <fuchsia/examples/llcpp/fidl.h>
    #include <lib/fdio/directory.h>
    #include <lib/zx/channel.h>
    #include <zircon/status.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.

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_sync"
        },
        "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.

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) {
  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);
  // Create a synchronous-only client to the Echo protocol.
  ::llcpp::fuchsia::examples::Echo::SyncClient client(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 succesfully
    ZX_ASSERT(result.ok());

    llcpp::fuchsia::examples::Echo::EventHandlers handlers{
        .on_string =
            [](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
              std::string reply_string(message->response.data(), message->response.size());
              std::cout << "Got event: " << reply_string << std::endl;
              return ZX_OK;
            },
        .unknown = []() { return ZX_ERR_INVALID_ARGS; }};
    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    ZX_ASSERT(client.HandleEvents(handlers).ok());
  }

  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][server-handler] is called with these arguments, binding the channel to the server implementation. The other end of this channel is then used to initialized the client object.

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.

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) {
  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);
  // Create a synchronous-only client to the Echo protocol.
  ::llcpp::fuchsia::examples::Echo::SyncClient client(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 succesfully
    ZX_ASSERT(result.ok());

    llcpp::fuchsia::examples::Echo::EventHandlers handlers{
        .on_string =
            [](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
              std::string reply_string(message->response.data(), message->response.size());
              std::cout << "Got event: " << reply_string << std::endl;
              return ZX_OK;
            },
        .unknown = []() { return ZX_ERR_INVALID_ARGS; }};
    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    ZX_ASSERT(client.HandleEvents(handlers).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 handlers struct, where each member corresponds to the handler for one of the events of the protocol.

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

int main(int argc, const char** argv) {
  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);
  // Create a synchronous-only client to the Echo protocol.
  ::llcpp::fuchsia::examples::Echo::SyncClient client(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 succesfully
    ZX_ASSERT(result.ok());

    llcpp::fuchsia::examples::Echo::EventHandlers handlers{
        .on_string =
            [](llcpp::fuchsia::examples::Echo::OnStringResponse* message) {
              std::string reply_string(message->response.data(), message->response.size());
              std::cout << "Got event: " << reply_string << std::endl;
              return ZX_OK;
            },
        .unknown = []() { return ZX_ERR_INVALID_ARGS; }};
    // Block to receive exactly one event from the server, which is handled using
    // the event handlers defined above.
    ZX_ASSERT(client.HandleEvents(handlers).ok());
  }

  return 0;
}

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:

    fx set core.x64 --with //examples/fidl/llcpp/server --with
    //examples/fidl/client/client_sync --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-sync#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).

[189209.659] 859216:859218> Running echo server
[189209.778] 859216:859218> echo_server_llcpp: Incoming connection for fuchsia.examples.Echo
[189209.803] 859554:859556> Got response: hello
[189209.804] 859554:859556> Got event: hi