實作 C++ FIDL 伺服器

必要條件

本教學課程以網域物件教學課程為基礎。如需 FIDL 的完整教學課程,請參閱總覽

總覽

本教學課程說明如何為 FIDL 通訊協定 (fuchsia.examples/Echo) 實作伺服器,並在 Fuchsia 上執行。這個通訊協定包含每種類型的一個方法:單向方法、雙向方法和事件:

@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.
        "//sdk/lib/async-loop:async-loop-cpp",
      ]
    }
    
    
  2. 這個元件會設定為執行伺服器可執行檔。元件是 Fuchsia 上執行軟體的單位。元件會由其資訊清單檔案描述。在這種情況下,meta/server.cml 會將 echo-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. 將伺服器新增至建構設定。這項操作只需執行一次:

    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.
    "//sdk/lib/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/log_settings.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();
  fuchsia_logging::LogSettingsBuilder builder;
  builder.WithDispatcher(dispatcher).BuildAndInitialize();

  // 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();
  fuchsia_logging::LogSettingsBuilder builder;
  builder.WithDispatcher(dispatcher).BuildAndInitialize();

  // 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 中。