C++ 中的协议请求管道

前提条件

本教程基于 C++ 入门教程

概览

在 Fuchsia 上使用 FIDL 的一个常见方面是跨 协议许多 FIDL 消息都包含客户端或服务器端 信道,其中的信道用于通过不同的 FIDL 进行通信 协议。在这种情况下,客户端允许向指定的 协议,而服务器端必须实现指定的协议。一个 客户端和服务器端的备用术语是协议和协议 请求。

本教程涵盖以下内容:

  • 这些客户端和服务器的使用结束,无论是在 FIDL 中还是在 C++ FIDL 绑定。
  • 协议请求管道模式及其优势。

本教程的完整示例代码位于 //examples/fidl/cpp/request_pipelining

FIDL 协议

本教程将实现 EchoLauncher 协议 fuchsia.examples 库:

@discoverable
closed protocol EchoLauncher {
    strict GetEcho(struct {
        echo_prefix string:MAX_STRING_LENGTH;
    }) -> (resource struct {
        response client_end:Echo;
    });
    strict GetEchoPipelined(resource struct {
        echo_prefix string:MAX_STRING_LENGTH;
        request server_end:Echo;
    });
};

该协议可让客户端检索 Echo 的实例 协议。客户端可以指定前缀和生成的 Echo 实例 会向每个响应添加该前缀。

为此,您可以使用以下两种方法:

  • GetEcho:接受前缀作为请求,并使用 连接到 Echo 协议实现的通道。更新后 在响应收到客户端一端时,客户端可以开始发出请求 使用客户端的 Echo 协议。
  • GetEchoPipelined:将通道的服务器端作为请求之一 参数,并将 Echo 的实现与其绑定。客户 则视为客户端已发送请求,并且 在调用 GetEchoPipelined 后开始对该频道发出 Echo 请求。

顾名思义,后者使用一种称为协议请求的模式。 是首选方法本教程同时实现了 方法。

实现服务器

实现 Echo 协议

这种 Echo 实现允许指定前缀,以便 区分 Echo 服务器的不同实例:

// Implementation of the Echo protocol that prepends a prefix to every response.
class EchoImpl final : public fidl::Server<fuchsia_examples::Echo> {
 public:
  explicit EchoImpl(std::string prefix) : prefix_(prefix) {}
  // This method is not used in the request pipelining example, so requests are ignored.
  void SendString(SendStringRequest& request, SendStringCompleter::Sync& completer) override {}

  void EchoString(EchoStringRequest& request, EchoStringCompleter::Sync& completer) override {
    FX_LOGS(INFO) << "Got echo request for prefix " << prefix_;
    completer.Reply(prefix_ + request.value());
  }

  const std::string prefix_;
};

SendString 处理程序为空,因为客户端仅使用 EchoString

实现 EchoLauncher 协议

// Implementation of EchoLauncher. Each method creates an instance of EchoImpl
// with the specified prefix.
class EchoLauncherImpl final : public fidl::Server<fuchsia_examples::EchoLauncher> {
 public:
  explicit EchoLauncherImpl(async_dispatcher_t* dispatcher) : dispatcher_(dispatcher) {}

  void GetEcho(GetEchoRequest& request, GetEchoCompleter::Sync& completer) override {
    FX_LOGS(INFO) << "Got non-pipelined request";
    auto [client_end, server_end] = fidl::Endpoints<fuchsia_examples::Echo>::Create();
    fidl::BindServer(dispatcher_, std::move(server_end),
                     std::make_unique<EchoImpl>(request.echo_prefix()));
    completer.Reply(std::move(client_end));
  }

  void GetEchoPipelined(GetEchoPipelinedRequest& request,
                        GetEchoPipelinedCompleter::Sync& completer) override {
    FX_LOGS(INFO) << "Got pipelined request";
    fidl::BindServer(dispatcher_, std::move(request.request()),
                     std::make_unique<EchoImpl>(request.echo_prefix()));
  }

  async_dispatcher_t* dispatcher_;
};

对于 GetEcho,代码首先需要实例化通道两端。它 然后,使用服务器端启动一个 Echo 实例,并发送响应 返回给客户端对于 GetEchoPipelined,客户端已完成 都是创建频道两端的工作保留一端并超过 将另一个对象绑定到服务器,所以代码只需要将服务器端 移到新的 EchoImpl

提供 EchoLauncher 协议

主循环与 服务器教程,但提供 EchoLauncher,而不是 Echo

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

  component::OutgoingDirectory outgoing = component::OutgoingDirectory(dispatcher);
  zx::result result = outgoing.ServeFromStartupInfo();
  if (result.is_error()) {
    FX_LOGS(ERROR) << "Failed to serve outgoing directory: " << result.status_string();
    return -1;
  }

  result = outgoing.AddUnmanagedProtocol<fuchsia_examples::EchoLauncher>(
      [dispatcher](fidl::ServerEnd<fuchsia_examples::EchoLauncher> server_end) {
        FX_LOGS(INFO) << "Incoming connection for "
                      << fidl::DiscoverableProtocolName<fuchsia_examples::EchoLauncher>;
        fidl::BindServer(dispatcher, std::move(server_end),
                         std::make_unique<EchoLauncherImpl>(dispatcher));
      });
  if (result.is_error()) {
    FX_LOGS(ERROR) << "Failed to add EchoLauncher protocol: " << result.status_string();
    return -1;
  }

  FX_LOGS(INFO) << "Running echo launcher server" << std::endl;
  loop.Run();
  return 0;
}

构建服务器

(可选)要检查设置是否正确,请尝试构建服务器:

  1. 将您的 GN build 配置为包含服务器:

    fx set core.x64 --with //examples/fidl/cpp/request_pipelining/server:echo-server
    
  2. 构建 Fuchsia 映像:

    fx build
    

实现客户端

连接到 EchoLauncher 服务器后,客户端 代码使用 GetEcho 连接到 Echo 的一个实例,使用 GetEcho 连接到另一个实例 GetEchoPipelined,然后对每个实例发出 EchoString 请求。

非流水线客户端

以下是非流水线代码:

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

  // Connect to the EchoLauncher protocol
  zx::result launcher_client_end = component::Connect<fuchsia_examples::EchoLauncher>();
  ZX_ASSERT(launcher_client_end.is_ok());
  fidl::Client launcher(std::move(*launcher_client_end), dispatcher);

  // Make a non-pipelined request to get an instance of Echo
  launcher->GetEcho({"non pipelined: "})
      .ThenExactlyOnce([&](fidl::Result<fuchsia_examples::EchoLauncher::GetEcho>& result) {
        ZX_ASSERT(result.is_ok());
        // Take the Echo client end in the response, bind it to another client, and
        // make an EchoString request on it.
        fidl::SharedClient echo(std::move(result->response()), dispatcher);
        echo->EchoString({"hello!"})
            .ThenExactlyOnce(
                // Clone |echo| into the callback so that the client
                // is only destroyed after we receive the response.
                [&, echo = echo.Clone()](fidl::Result<fuchsia_examples::Echo::EchoString>& result) {
                  ZX_ASSERT(result.is_ok());
                  FX_LOGS(INFO) << "Got echo response " << result->response();
                  if (++num_responses == 2) {
                    loop.Quit();
                  }
                });
      });

  auto [client_end, server_end] = fidl::Endpoints<fuchsia_examples::Echo>::Create();
  // Make a pipelined request to get an instance of Echo
  ZX_ASSERT(launcher->GetEchoPipelined({"pipelined: ", std::move(server_end)}).is_ok());
  // A client can be initialized using the client end without waiting for a response
  fidl::Client echo_pipelined(std::move(client_end), dispatcher);
  echo_pipelined->EchoString({"hello!"})
      .ThenExactlyOnce([&](fidl::Result<fuchsia_examples::Echo::EchoString>& result) {
        ZX_ASSERT(result.is_ok());
        FX_LOGS(INFO) << "Got echo response " << result->response();
        if (++num_responses == 2) {
          loop.Quit();
        }
      });

  loop.Run();
  return num_responses == 2 ? 0 : 1;
}

此代码有两层回调:

  • 外层负责处理启动器 GetEcho 响应。
  • 内层处理 EchoString 响应。

GetEcho 响应回调内,代码绑定返回的客户端 到 fidl::SharedClient<Echo>,并将克隆放入 EchoString 回调,以便延长客户端的生命周期,直到收到 echo 响应 该事件很有可能是在顶级回调返回之后。

流水线客户端

尽管必须先创建一对端点,但流水线代码 更简单:

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

  // Connect to the EchoLauncher protocol
  zx::result launcher_client_end = component::Connect<fuchsia_examples::EchoLauncher>();
  ZX_ASSERT(launcher_client_end.is_ok());
  fidl::Client launcher(std::move(*launcher_client_end), dispatcher);

  // Make a non-pipelined request to get an instance of Echo
  launcher->GetEcho({"non pipelined: "})
      .ThenExactlyOnce([&](fidl::Result<fuchsia_examples::EchoLauncher::GetEcho>& result) {
        ZX_ASSERT(result.is_ok());
        // Take the Echo client end in the response, bind it to another client, and
        // make an EchoString request on it.
        fidl::SharedClient echo(std::move(result->response()), dispatcher);
        echo->EchoString({"hello!"})
            .ThenExactlyOnce(
                // Clone |echo| into the callback so that the client
                // is only destroyed after we receive the response.
                [&, echo = echo.Clone()](fidl::Result<fuchsia_examples::Echo::EchoString>& result) {
                  ZX_ASSERT(result.is_ok());
                  FX_LOGS(INFO) << "Got echo response " << result->response();
                  if (++num_responses == 2) {
                    loop.Quit();
                  }
                });
      });

  auto [client_end, server_end] = fidl::Endpoints<fuchsia_examples::Echo>::Create();
  // Make a pipelined request to get an instance of Echo
  ZX_ASSERT(launcher->GetEchoPipelined({"pipelined: ", std::move(server_end)}).is_ok());
  // A client can be initialized using the client end without waiting for a response
  fidl::Client echo_pipelined(std::move(client_end), dispatcher);
  echo_pipelined->EchoString({"hello!"})
      .ThenExactlyOnce([&](fidl::Result<fuchsia_examples::Echo::EchoString>& result) {
        ZX_ASSERT(result.is_ok());
        FX_LOGS(INFO) << "Got echo response " << result->response();
        if (++num_responses == 2) {
          loop.Quit();
        }
      });

  loop.Run();
  return num_responses == 2 ? 0 : 1;
}

客户端教程不同,异步循环会完整运行 一次,即同时运行非流水线代码和流水线代码, 并注意观察操作顺序客户端会跟踪 这样,当没有更多消息时,它就可以退出循环 预期。

构建客户端

(可选)要检查是否正确,请尝试构建客户端:

  1. 将您的 GN build 配置为包含服务器:

    fx set core.x64 --with //examples/fidl/cpp/request_pipelining/client:echo-client
    
  2. 构建 Fuchsia 映像:

    fx build
    

运行示例代码

在本教程中, 领域 组件是 用于声明 fuchsia.examples.Echofuchsia.examples.EchoLauncher

  1. 配置 build,使其包含提供的软件包,其中包含 echo 领域、服务器和客户端:

    fx set core.x64 --with //examples/fidl/cpp/request_pipelining
    
  2. 构建 Fuchsia 映像:

    fx build
    
  3. 运行 echo_realm 组件。这会创建客户端和服务器组件 并路由功能:

    ffx component run /core/ffx-laboratory:echo_realm fuchsia-pkg://fuchsia.com/echo-launcher-cpp#meta/echo_realm.cm
    
  4. 启动 echo_client 实例:

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

在客户端尝试连接到 EchoLauncher 协议。您应该会看到类似如下所示的输出 在设备日志 (ffx log) 中:

[echo_server][I] Running echo launcher server
[echo_server][I] Incoming connection for fuchsia.examples.EchoLauncher
[echo_server][I] Got non-pipelined request
[echo_server][I] Got pipelined request
[echo_server][I] Got echo request for prefix pipelined:
[echo_server][I] Got echo request for prefix non pipelined:
[echo_client][I] Got echo response pipelined: hello!
[echo_client][I] Got echo response non pipelined: hello!

根据打印顺序,您可以看到流水线处理速度较快。通过 echo 响应首先到达流水线,即使非 流水线请求首先发送,因为请求流水线可以节省往返时间 客户端和服务器之间的通信请求管道也能简化代码。

有关协议请求管道(包括如何处理 则请参阅 FIDL API 评分准则

终止领域组件以停止执行并清理组件 实例:

ffx component destroy /core/ffx-laboratory:echo_realm