实现 C++ FIDL 服务器

前提条件

本教程以网域对象教程为基础。如需查看完整的 FIDL 教程,请参阅概览

概览

本教程介绍了如何为 FIDL 协议 (fuchsia.examples/Echo) 实现服务器并在 Fuchsia 上运行该服务器。此协议每种方法均有 1 种:单向方法、双向方法和事件:

@discoverable
closed protocol Echo {
    strict EchoString(struct {
        value string:MAX_STRING_LENGTH;
    }) -> (struct {
        response string:MAX_STRING_LENGTH;
    });
    strict SendString(struct {
        value string:MAX_STRING_LENGTH;
    });
    strict -> OnString(struct {
        response string:MAX_STRING_LENGTH;
    });
};

如需详细了解 FIDL 方法和消息传递模型,请参阅 FIDL 概念页面。

本文档介绍了如何完成以下任务:

服务器结构示例

本教程附带的示例代码位于您的 Fuchsia 结算账号://examples/fidl/cpp/server。它由一个服务器组件及其包含的软件包组成。如需详细了解如何构建组件,请参阅构建组件

如需启动并运行服务器组件,请在 //examples/fidl/cpp/server/BUILD.gn 中定义三个目标:

  1. 服务器的原始可执行文件。这将生成一个具有指定输出名称的二进制文件,该二进制文件可在 Fuchsia 上运行:

    executable("bin") {
      output_name = "fidl_echo_cpp_server"
      sources = [ "main.cc" ]
      deps = [
        "//examples/fidl/fuchsia.examples:fuchsia.examples_cpp",
    
        # This library is used to log messages.
        "//sdk/lib/syslog/cpp",
    
        # This library is used to publish capabilities, e.g. protocols,
        # to the component's outgoing directory.
        "//sdk/lib/component/outgoing/cpp",
    
        # This library provides an the asynchronous event loop implementation.
        "//zircon/system/ulib/async-loop:async-loop-cpp",
      ]
    }
    
    
  2. 用于运行服务器可执行文件的组件。组件是 Fuchsia 上的软件执行单元。组件由其清单文件描述。在本例中,meta/server.cmlecho-server 配置为在 :bin 中运行 fidl_echo_cpp_server 的可执行组件。

    fuchsia_component("echo-server") {
      component_name = "echo_server"
      manifest = "meta/server.cml"
      deps = [ ":bin" ]
    }
    
    

    服务器组件清单位于 //examples/fidl/cpp/server/meta/server.cml。清单中的二进制文件名称必须与 BUILD.gn 中定义的 executable 的输出名称一致。

    {
        include: [ "syslog/client.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_cpp_server",
        },
    
        // Capabilities provided by this component.
        capabilities: [
            { protocol: "fuchsia.examples.Echo" },
        ],
        expose: [
            {
                protocol: "fuchsia.examples.Echo",
                from: "self",
            },
        ],
    }
    
    
  3. 然后将该组件放入软件包(即 Fuchsia 上软件分发的单元)中。在本例中,该软件包仅包含一个组件。

    fuchsia_package("echo-cpp-server") {
      package_name = "echo-cpp-server"
      deps = [ ":echo-server" ]
    }
    
    

构建服务器

您可以通过以下方式构建服务器软件包:

  1. 将服务器添加到您的 build 配置中。此操作只需执行一次:

    fx set core.x64 --with //examples/fidl/cpp/server
    
  2. 构建服务器软件包:

    fx build examples/fidl/cpp/server
    

实现 FIDL 协议

EchoImpl 可实现 fuchsia.examples/Echo 协议的服务器请求处理程序。为此,EchoImpl 继承自生成的纯虚拟服务器接口 fidl::Server<fuchsia_examples::Echo>,并替换其单向调用和双向调用对应的纯虚拟方法:

class EchoImpl : public fidl::Server<fuchsia_examples::Echo> {
 public:
  // The handler for `fuchsia.examples/Echo.EchoString`.
  //
  // For two-way methods (those with a response) like this one, the completer is
  // used complete the call: either to send the reply via |completer.Reply|, or
  // close the channel via |completer.Close|.
  //
  // |EchoStringRequest| exposes the same API as the request struct domain
  // object, that is |fuchsia_examples::EchoEchoStringRequest|.
  void EchoString(EchoStringRequest& request, EchoStringCompleter::Sync& completer) override {
    // Call |Reply| to reply synchronously with the request value.
    completer.Reply({{.response = request.value()}});
  }

  // The handler for `fuchsia.examples/Echo.SendString`.
  //
  // For fire-and-forget methods like this one, the completer is normally not
  // used, but its |Close(zx_status_t)| method can be used to close the channel,
  // either when the protocol has reached its intended terminal state or the
  // server encountered an unrecoverable error.
  //
  // |SendStringRequest| exposes the same API as the request struct domain
  // object, that is |fuchsia_examples::EchoSendStringRequest|.
  void SendString(SendStringRequest& request, SendStringCompleter::Sync& completer) override {
    ZX_ASSERT(binding_ref_.has_value());

    // Handle a SendString request by sending an |OnString| event (an
    // unsolicited server-to-client message) back to the client.
    fit::result result = fidl::SendEvent(*binding_ref_)->OnString({request.value()});
    if (!result.is_ok()) {
      FX_LOGS(ERROR) << "Error sending event: " << result.error_value();
    }
  }

  // ... other methods from examples/fidl/cpp/server/main.cc omitted, to be covered later.

 private:
  // `ServerBindingRef` can be used to:
  // - Control the binding, such as to unbind the server from the channel or
  //   close the channel.
  // - Send events back to the client.
  // See the documentation comments on |fidl::ServerBindingRef|.
  std::optional<fidl::ServerBindingRef<fuchsia_examples::Echo>> binding_ref_;
};

将实现绑定到服务器端点

实现请求处理程序只是成功的一半。服务器需要能够监控到达服务器端点上的新消息。为此,EchoImpl 又定义了两个方法:一个是 BindSelfManagedServer 静态出厂函数,另一个是创建新的 EchoImpl 实例来处理新服务器端点 fidl::ServerEnd<fuchsia_examples::Echo> 上的请求,另一个是连接断开时调用的 OnUnbound 方法:

/* Inside `class EchoImpl {`... */

  // Bind a new implementation of |EchoImpl| to handle requests coming from
  // the server endpoint |server_end|.
  static void BindSelfManagedServer(async_dispatcher_t* dispatcher,
                                    fidl::ServerEnd<fuchsia_examples::Echo> server_end) {
    // Create a new instance of |EchoImpl|.
    std::unique_ptr impl = std::make_unique<EchoImpl>();
    EchoImpl* impl_ptr = impl.get();

    // |fidl::BindServer| takes a FIDL protocol server implementation and a
    // channel. It asynchronously reads requests off the channel, decodes them
    // and dispatches them to the correct handler on the server implementation.
    //
    // The FIDL protocol server implementation can be passed as a
    // |std::shared_ptr|, |std::unique_ptr|, or raw pointer. For shared and
    // unique pointers, the binding will manage the lifetime of the
    // implementation object. For raw pointers, it's up to the caller to ensure
    // that the implementation object outlives the binding but does not leak.
    //
    // See the documentation comment of |fidl::BindServer|.
    fidl::ServerBindingRef binding_ref = fidl::BindServer(
        dispatcher, std::move(server_end), std::move(impl), std::mem_fn(&EchoImpl::OnUnbound));
    // Put the returned |binding_ref| into the |EchoImpl| object.
    impl_ptr->binding_ref_.emplace(std::move(binding_ref));
  }

  // This method is passed to the |BindServer| call as the last argument,
  // which means it will be called when the connection is torn down.
  // In this example we use it to log some connection lifecycle information.
  // Production code could do more things such as resource cleanup.
  void OnUnbound(fidl::UnbindInfo info, fidl::ServerEnd<fuchsia_examples::Echo> server_end) {
    // |is_user_initiated| returns true if the server code called |Close| on a
    // completer, or |Unbind| / |Close| on the |binding_ref_|, to proactively
    // teardown the connection. These cases are usually part of normal server
    // shutdown, so logging is unnecessary.
    if (info.is_user_initiated()) {
      return;
    }
    if (info.is_peer_closed()) {
      // If the peer (the client) closed their endpoint, log that as INFO.
      FX_LOGS(INFO) << "Client disconnected";
    } else {
      // Treat other unbind causes as errors.
      FX_LOGS(ERROR) << "Server error: " << info;
    }
  }

发布协议实现

实现 FIDL 协议的组件可以将该 FIDL 协议公开给其他组件。 开放协议的生命周期中更详细地介绍了这一完整流程。我们可以使用 C++ 组件运行时库中的 component::OutgoingDirectory 来执行繁重的工作。

如需依赖于组件运行时库,请执行以下操作:

executable("bin") {
  output_name = "fidl_echo_cpp_server"
  sources = [ "main.cc" ]
  deps = [
    "//examples/fidl/fuchsia.examples:fuchsia.examples_cpp",

    # This library is used to log messages.
    "//sdk/lib/syslog/cpp",

    # This library is used to publish capabilities, e.g. protocols,
    # to the component's outgoing directory.
    "//sdk/lib/component/outgoing/cpp",

    # This library provides an the asynchronous event loop implementation.
    "//zircon/system/ulib/async-loop:async-loop-cpp",
  ]
}

examples/fidl/cpp/server/main.cc 的顶部导入该库:

#include <fidl/fuchsia.examples/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/component/outgoing/cpp/outgoing_directory.h>
#include <lib/syslog/cpp/macros.h>

提供组件的传出目录:

int main(int argc, const char** argv) {
  // The event loop is used to asynchronously listen for incoming connections
  // and requests from the client. The following initializes the loop, and
  // obtains the dispatcher, which will be used when binding the server
  // implementation to a channel.
  async::Loop loop(&kAsyncLoopConfigNeverAttachToThread);
  async_dispatcher_t* dispatcher = loop.dispatcher();

  // Create an |OutgoingDirectory| instance.
  //
  // The |component::OutgoingDirectory| class serves the outgoing directory for
  // our component. This directory is where the outgoing FIDL protocols are
  // installed so that they can be provided to other components.
  component::OutgoingDirectory outgoing = component::OutgoingDirectory(dispatcher);

  // The `ServeFromStartupInfo()` function sets up the outgoing directory with
  // the startup handle. The startup handle is a handle provided to every
  // component by the system, so that they can serve capabilities (e.g. FIDL
  // protocols) to other components.
  zx::result result = outgoing.ServeFromStartupInfo();
  if (result.is_error()) {
    FX_LOGS(ERROR) << "Failed to serve outgoing directory: " << result.status_string();
    return -1;
  }

  // ...

提供协议

然后,服务器会使用 outgoing.AddProtocol 注册 Echo 协议。

int main(int argc, const char** argv) {
  // The event loop is used to asynchronously listen for incoming connections
  // and requests from the client. The following initializes the loop, and
  // obtains the dispatcher, which will be used when binding the server
  // implementation to a channel.
  async::Loop loop(&kAsyncLoopConfigNeverAttachToThread);
  async_dispatcher_t* dispatcher = loop.dispatcher();

  // Create an |OutgoingDirectory| instance.
  //
  // The |component::OutgoingDirectory| class serves the outgoing directory for
  // our component. This directory is where the outgoing FIDL protocols are
  // installed so that they can be provided to other components.
  component::OutgoingDirectory outgoing = component::OutgoingDirectory(dispatcher);

  // The `ServeFromStartupInfo()` function sets up the outgoing directory with
  // the startup handle. The startup handle is a handle provided to every
  // component by the system, so that they can serve capabilities (e.g. FIDL
  // protocols) to other components.
  zx::result result = outgoing.ServeFromStartupInfo();
  if (result.is_error()) {
    FX_LOGS(ERROR) << "Failed to serve outgoing directory: " << result.status_string();
    return -1;
  }

  // Register a handler for components trying to connect to fuchsia.examples.Echo.
  result = outgoing.AddUnmanagedProtocol<fuchsia_examples::Echo>(
      [dispatcher](fidl::ServerEnd<fuchsia_examples::Echo> server_end) {
        FX_LOGS(INFO) << "Incoming connection for "
                      << fidl::DiscoverableProtocolName<fuchsia_examples::Echo>;
        EchoImpl::BindSelfManagedServer(dispatcher, std::move(server_end));
      });
  if (result.is_error()) {
    FX_LOGS(ERROR) << "Failed to add Echo protocol: " << result.status_string();
    return -1;
  }

  FX_LOGS(INFO) << "Running C++ echo server with natural types";

  // This runs the event loop and blocks until the loop is quit or shutdown.
  // See documentation comments on |async::Loop|.
  loop.Run();
  return 0;
}

调用 AddProtocol 会在 FIDL 协议的名称(fidl::DiscoverableProtocolName<fuchsia_examples::Echo>,即字符串 "fuchsia.examples.Echo")安装一个处理程序。当客户端组件连接到 fuchsia.examples.Echo 时,outgoing 将使用与来自客户端的客户端端点相对应的服务器端点调用我们创建的 lambda 函数,此 lambda 函数将调用上面详述的 EchoImpl::BindSelfManagedServer 以将服务器端点绑定到 EchoImpl 的新实例。

我们的主方法将继续监听异步循环上的传入请求。

测试服务器

构建服务器后,您可以通过以下命令在正在运行的 Fuchsia 模拟器实例上运行该示例:

ffx component run /core/ffx-laboratory:echo-server fuchsia-pkg://fuchsia.com/echo-cpp-server#meta/echo_server.cm

您应该会在设备日志 (ffx log) 中看到类似于以下内容的输出:

[ffx-laboratory:echo_server][][I] Running C++ echo server with natural types

服务器现在正在运行并在等待传入请求。下一步是编写一个发送 Echo 协议请求的客户端。目前,您可以直接终止服务器组件:

注意
ffx component destroy /core/ffx-laboratory:echo_server

使用有线网域对象处理请求

上述教程使用自然网域对象实现服务器:服务器接收以自然网域对象表示的请求,并发送使用自然网域对象编码的回复。在针对性能和堆分配进行优化时,可以实现讲有线域对象的服务器,即有线服务器。以下是重新编写为使用有线域对象的 EchoImpl

class EchoImpl final : public fidl::WireServer<fuchsia_examples::Echo> {
 public:
  // The handler for `fuchsia.examples/Echo.EchoString`.
  //
  // For two-way methods (those with a response) like this one, the completer is
  // used complete the call: either to send the reply via |completer.Reply|, or
  // close the channel via |completer.Close|.
  //
  // |EchoStringRequestView| exposes the same API as a pointer to the request
  // struct domain object, that is
  // |fuchsia_examples::wire::EchoEchoStringRequest*|.
  void EchoString(EchoStringRequestView request, EchoStringCompleter::Sync& completer) override {
    // Call |Reply| to reply synchronously with the request value.
    completer.Reply(request->value);
  }

  // The handler for `fuchsia.examples/Echo.SendString`.
  //
  // For fire-and-forget methods like this one, the completer is normally not
  // used, but its |Close(zx_status_t)| method can be used to close the channel,
  // either when the protocol has reached its intended terminal state or the
  // server encountered an unrecoverable error.
  //
  // |SendStringRequestView| exposes the same API as a pointer to the request
  // struct domain object, that is
  // |fuchsia_examples::wire::EchoSendStringRequest*|.
  void SendString(SendStringRequestView request, SendStringCompleter::Sync& completer) override {
    // Handle a SendString request by sending an |OnString| event (an
    // unsolicited server-to-client message) back to the client.
    fidl::Status status = fidl::WireSendEvent(binding_)->OnString(request->value);
    if (!status.ok()) {
      FX_LOGS(ERROR) << "Error sending event: " << status.error();
    }
  }

  // ... |BindSelfManagedServer| etc omitted. Those stay the same.
};

线路服务器中使用的相关类和函数具有与自然服务器中使用的形状和形状类似的形状。当针对不同的类或函数调用其他类或函数时,对应的线上类通常带有 Wire 前缀。指针与引用和参数结构之间也存在细微差异:

  • 由自然服务器实现的服务器接口为 fidl::Server<fuchsia_examples::Echo>。由有线服务器实现的服务器接口为 fidl::WireServer<fuchsia_examples::Echo>

  • 自然服务器中的处理程序函数接受对请求消息的引用。Reply 方法接受一个参数,即响应载荷网域对象:

    void EchoString(EchoStringRequest& request, EchoStringCompleter::Sync& completer) override {
      // Call |Reply| to reply synchronously with the request value.
      completer.Reply({{.response = request.value()}});
    }
    

    而传输服务器中的处理程序函数则接受请求消息的视图(类似于指针)。当响应载荷是结构体时,Reply 方法会将响应载荷中的结构体字段列表展平为单独的参数(此处为单个 fidl::StringView 参数):

    void EchoString(EchoStringRequestView request, EchoStringCompleter::Sync& completer) override {
      // Call |Reply| to reply synchronously with the request value.
      completer.Reply(request->value);
    }
    
  • 发送自然类型的事件的函数为 fidl::SendEvent。使用传输类型发送事件的函数为 fidl::WireSendEvent。发送事件时,结构体字段也会展平为单独的参数。

同一个 fidl::BindServer 函数可用于绑定自然服务器或线路服务器。

如需查看线路服务器的完整示例代码,请访问您的 Fuchsia 结算页面,网址为 //examples/fidl/cpp/server/wire