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 the component
Create a new component project at examples/fidl/llcpp/client
:
Add a
main()
function toexamples/fidl/llcpp/client/main.cc
:int main(int argc, const char** argv) { std::cout << "Hello, world!" << std::endl; }
Declare a target for the client in
examples/fidl/llcpp/client/BUILD.gn
:import("//build/components.gni") # Declare an executable for the client. executable("bin") { output_name = "fidl_echo_llcpp_client" sources = [ "main.cc" ] } fuchsia_component("echo-client") { component_name = "echo_client" manifest = "meta/client.cml" deps = [ ":bin" ] }
Add a component manifest in
examples/fidl/llcpp/client/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", }, // Capabilities used by this component. use: [ { protocol: "fuchsia.examples.Echo" }, ], }
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:echo-client
Build the Fuchsia image:
fx build
Edit GN dependencies
Add the following dependencies:
deps = [ "//examples/fidl/fuchsia.examples:fuchsia.examples_llcpp", "//sdk/lib/fdio", "//zircon/system/ulib/async-loop:async-loop-cpp", "//zircon/system/ulib/async-loop:async-loop-default", "//zircon/system/ulib/fidl", "//zircon/system/ulib/service:service-llcpp", ]
Then, include them in
main.cc
:#include <fidl/fuchsia.examples/cpp/wire.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fidl/llcpp/client.h> #include <lib/service/llcpp/service.h> #include <zircon/assert.h> #include <iostream>
These dependencies are explained in the server tutorial.
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();
// |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, here we demonstrate
// using |service::ConnectAt| relative to some service directory.
// One may also directly call |Connect| to use the default service directory.
auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
ZX_ASSERT(client_end.status_value() == ZX_OK);
// Define the event handler for the client. The OnString event handler prints the event.
class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
public:
explicit EventHandler(async::Loop& loop) : loop_(loop) {}
void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
std::string response(event->response.data(), event->response.size());
std::cout << "Got event: " << response << std::endl;
loop_.Quit();
}
void on_fidl_error(fidl::UnbindInfo error) override {
std::cerr << "Connection terminated with error: " << error << std::endl;
abort();
}
private:
async::Loop& loop_;
};
EventHandler handler(loop);
// Create a client to the Echo protocol.
fidl::WireClient client(std::move(*client_end), dispatcher, &handler);
// Make an EchoString call, passing it a lambda to handle the result asynchronously.
// |result| contains the method response or a transport error if applicable.
client->EchoString("hello").Then(
[&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
ZX_ASSERT_MSG(result.ok(), "EchoString failed: %s",
result.error().FormatDescription().c_str());
auto* response = result.Unwrap_NEW();
std::string reply(response->response.data(), response->response.size());
std::cout << "Got response (result callback): " << reply << std::endl;
loop.Quit();
});
loop.Run();
loop.ResetQuit();
// Make a synchronous EchoString call, which blocks until it receives the response,
// then returns a WireResult object for the response.
fidl::WireResult result_sync = client.sync()->EchoString("hello");
ZX_ASSERT(result_sync.ok());
std::string reply_string(result_sync.Unwrap_NEW()->response.data(),
result_sync.Unwrap_NEW()->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.
fidl::Status status_oneway = client->SendString("hi");
// Check for any synchronous errors.
ZX_ASSERT(status_oneway.ok());
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();
// |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, here we demonstrate
// using |service::ConnectAt| relative to some service directory.
// One may also directly call |Connect| to use the default service directory.
auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
ZX_ASSERT(client_end.status_value() == ZX_OK);
// Define the event handler for the client. The OnString event handler prints the event.
class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
public:
explicit EventHandler(async::Loop& loop) : loop_(loop) {}
void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
std::string response(event->response.data(), event->response.size());
std::cout << "Got event: " << response << std::endl;
loop_.Quit();
}
void on_fidl_error(fidl::UnbindInfo error) override {
std::cerr << "Connection terminated with error: " << error << std::endl;
abort();
}
private:
async::Loop& loop_;
};
EventHandler handler(loop);
// Create a client to the Echo protocol.
fidl::WireClient client(std::move(*client_end), dispatcher, &handler);
// Make an EchoString call, passing it a lambda to handle the result asynchronously.
// |result| contains the method response or a transport error if applicable.
client->EchoString("hello").Then(
[&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
ZX_ASSERT_MSG(result.ok(), "EchoString failed: %s",
result.error().FormatDescription().c_str());
auto* response = result.Unwrap_NEW();
std::string reply(response->response.data(), response->response.size());
std::cout << "Got response (result callback): " << reply << std::endl;
loop.Quit();
});
loop.Run();
loop.ResetQuit();
// Make a synchronous EchoString call, which blocks until it receives the response,
// then returns a WireResult object for the response.
fidl::WireResult result_sync = client.sync()->EchoString("hello");
ZX_ASSERT(result_sync.ok());
std::string reply_string(result_sync.Unwrap_NEW()->response.data(),
result_sync.Unwrap_NEW()->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.
fidl::Status status_oneway = client->SendString("hi");
// Check for any synchronous errors.
ZX_ASSERT(status_oneway.ok());
loop.Run();
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.
Initialize the client
In order to make Echo
requests to the server, initialize a client using the
client end of the channel from the previous step, the loop dispatcher, as well
as an event handler delegate:
int main(int argc, const char** argv) {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
async_dispatcher_t* dispatcher = loop.dispatcher();
// |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, here we demonstrate
// using |service::ConnectAt| relative to some service directory.
// One may also directly call |Connect| to use the default service directory.
auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
ZX_ASSERT(client_end.status_value() == ZX_OK);
// Define the event handler for the client. The OnString event handler prints the event.
class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
public:
explicit EventHandler(async::Loop& loop) : loop_(loop) {}
void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
std::string response(event->response.data(), event->response.size());
std::cout << "Got event: " << response << std::endl;
loop_.Quit();
}
void on_fidl_error(fidl::UnbindInfo error) override {
std::cerr << "Connection terminated with error: " << error << std::endl;
abort();
}
private:
async::Loop& loop_;
};
EventHandler handler(loop);
// Create a client to the Echo protocol.
fidl::WireClient client(std::move(*client_end), dispatcher, &handler);
// Make an EchoString call, passing it a lambda to handle the result asynchronously.
// |result| contains the method response or a transport error if applicable.
client->EchoString("hello").Then(
[&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
ZX_ASSERT_MSG(result.ok(), "EchoString failed: %s",
result.error().FormatDescription().c_str());
auto* response = result.Unwrap_NEW();
std::string reply(response->response.data(), response->response.size());
std::cout << "Got response (result callback): " << reply << std::endl;
loop.Quit();
});
loop.Run();
loop.ResetQuit();
// Make a synchronous EchoString call, which blocks until it receives the response,
// then returns a WireResult object for the response.
fidl::WireResult result_sync = client.sync()->EchoString("hello");
ZX_ASSERT(result_sync.ok());
std::string reply_string(result_sync.Unwrap_NEW()->response.data(),
result_sync.Unwrap_NEW()->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.
fidl::Status status_oneway = client->SendString("hi");
// Check for any synchronous errors.
ZX_ASSERT(status_oneway.ok());
loop.Run();
return 0;
}
The event handler delegate should be an object that implements the
fidl::AsyncEventHandler<Echo>
virtual interface, which has methods
corresponding to the events offered by the protocol (see
LLCPP event handlers). In this case, a local class is defined
with a method corresponding to the OnString
event. The handler prints the
string and quits the event loop. The class also overrides the on_fidl_error
method, which is called when the client encounters an error and is going to
teardown.
Send requests to the server
The code makes four requests to the server:
- An asynchronous
EchoString
call taking a result callback. - An asynchronous
EchoString
call taking a response callback. - A synchronous
EchoString
call. - A one way
SendString
request (async vs sync is not relevant for this case because it is a fire and forget method).
The client object works by overriding the dereference operator to return a
protocol specific client implementation, allowing calls such as
client->EchoString()
.
Asynchronous call with result callback
The asynchronous method call requires the request parameters followed by a result callback, which is called either when the method succeeds or an error happens.
int main(int argc, const char** argv) {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
async_dispatcher_t* dispatcher = loop.dispatcher();
// |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, here we demonstrate
// using |service::ConnectAt| relative to some service directory.
// One may also directly call |Connect| to use the default service directory.
auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
ZX_ASSERT(client_end.status_value() == ZX_OK);
// Define the event handler for the client. The OnString event handler prints the event.
class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
public:
explicit EventHandler(async::Loop& loop) : loop_(loop) {}
void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
std::string response(event->response.data(), event->response.size());
std::cout << "Got event: " << response << std::endl;
loop_.Quit();
}
void on_fidl_error(fidl::UnbindInfo error) override {
std::cerr << "Connection terminated with error: " << error << std::endl;
abort();
}
private:
async::Loop& loop_;
};
EventHandler handler(loop);
// Create a client to the Echo protocol.
fidl::WireClient client(std::move(*client_end), dispatcher, &handler);
// Make an EchoString call, passing it a lambda to handle the result asynchronously.
// |result| contains the method response or a transport error if applicable.
client->EchoString("hello").Then(
[&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
ZX_ASSERT_MSG(result.ok(), "EchoString failed: %s",
result.error().FormatDescription().c_str());
auto* response = result.Unwrap_NEW();
std::string reply(response->response.data(), response->response.size());
std::cout << "Got response (result callback): " << reply << std::endl;
loop.Quit();
});
loop.Run();
loop.ResetQuit();
// Make a synchronous EchoString call, which blocks until it receives the response,
// then returns a WireResult object for the response.
fidl::WireResult result_sync = client.sync()->EchoString("hello");
ZX_ASSERT(result_sync.ok());
std::string reply_string(result_sync.Unwrap_NEW()->response.data(),
result_sync.Unwrap_NEW()->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.
fidl::Status status_oneway = client->SendString("hi");
// Check for any synchronous errors.
ZX_ASSERT(status_oneway.ok());
loop.Run();
return 0;
}
Synchronous call
The client object also allows synchronous calls, which will block until the
response is received and return the response object. These may be selected
using the .sync()
accessor. (e.g. client.sync()->EchoString()
).
int main(int argc, const char** argv) {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
async_dispatcher_t* dispatcher = loop.dispatcher();
// |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, here we demonstrate
// using |service::ConnectAt| relative to some service directory.
// One may also directly call |Connect| to use the default service directory.
auto client_end = service::ConnectAt<fuchsia_examples::Echo>(*svc);
ZX_ASSERT(client_end.status_value() == ZX_OK);
// Define the event handler for the client. The OnString event handler prints the event.
class EventHandler : public fidl::WireAsyncEventHandler<fuchsia_examples::Echo> {
public:
explicit EventHandler(async::Loop& loop) : loop_(loop) {}
void OnString(fidl::WireEvent<fuchsia_examples::Echo::OnString>* event) override {
std::string response(event->response.data(), event->response.size());
std::cout << "Got event: " << response << std::endl;
loop_.Quit();
}
void on_fidl_error(fidl::UnbindInfo error) override {
std::cerr << "Connection terminated with error: " << error << std::endl;
abort();
}
private:
async::Loop& loop_;
};
EventHandler handler(loop);
// Create a client to the Echo protocol.
fidl::WireClient client(std::move(*client_end), dispatcher, &handler);
// Make an EchoString call, passing it a lambda to handle the result asynchronously.
// |result| contains the method response or a transport error if applicable.
client->EchoString("hello").Then(
[&](fidl::WireUnownedResult<fuchsia_examples::Echo::EchoString>& result) {
ZX_ASSERT_MSG(result.ok(), "EchoString failed: %s",
result.error().FormatDescription().c_str());
auto* response = result.Unwrap_NEW();
std::string reply(response->response.data(), response->response.size());
std::cout << "Got response (result callback): " << reply << std::endl;
loop.Quit();
});
loop.Run();
loop.ResetQuit();
// Make a synchronous EchoString call, which blocks until it receives the response,
// then returns a WireResult object for the response.
fidl::WireResult result_sync = client.sync()->EchoString("hello");
ZX_ASSERT(result_sync.ok());
std::string reply_string(result_sync.Unwrap_NEW()->response.data(),
result_sync.Unwrap_NEW()->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.
fidl::Status status_oneway = client->SendString("hi");
// Check for any synchronous errors.
ZX_ASSERT(status_oneway.ok());
loop.Run();
return 0;
}
In the synchronous case, a result object is returned, since the method call can fail. In the asynchronous or fire-and-forget case, a lightweight status object is returned, which communicates any synchronous errors.
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.
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
Build the Fuchsia image:
fx build
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#meta/echo_realm.cm
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_server][][I] Incoming connection for fuchsia.examples.Echo
[echo_client][][I] Got response (result callback): hello
[echo_client][][I] Got response (response callback): hello
[echo_client][][I] Got synchronous response: hello
[echo_client][][I] Got event: hi
Terminate the realm component to stop execution and clean up the component instances:
ffx component destroy /core/ffx-laboratory:echo_realm