必要條件
本教學課程以 C++ 入門教學課程為基礎。
總覽
在 Fuchsia 上使用 FIDL 時,常見的做法是在通訊協定之間傳遞通訊協定端點。許多 FIDL 訊息都包含管道的用戶端或伺服器端,管道則用於透過不同的 FIDL 通訊協定進行通訊。在這種情況下,用戶端可向指定通訊協定發出要求,而伺服器端則必須實作指定通訊協定。用戶端和伺服器端的替代詞彙是通訊協定和通訊協定要求。
本教學課程涵蓋下列主題:
- 這些用戶端和伺服器的使用情形會終止,無論是在 FIDL 或 C++ FIDL 繫結中都是如此。
- 通訊協定要求管道化模式及其優點。
本教學課程的完整範例程式碼位於 //examples/fidl/cpp/request_pipelining。
FIDL 通訊協定
本教學課程會實作 fuchsia.examples 程式庫的 EchoLauncher 通訊協定:
@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_;
};
由於用戶端只會使用 EchoString,因此 SendString 處理常式為空白。
實作 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;
}
建構伺服器
視需要建構伺服器,確認一切正常:
設定 GN 建構作業,加入伺服器:
fx set core.x64 --with //examples/fidl/cpp/request_pipelining/server:echo-server建構 Fuchsia 映像檔:
fx build
實作用戶端
這篇文章。連線至 EchoLauncher 伺服器後,用戶端程式碼會使用 GetEcho 連線至 Echo 的一個例項,並使用 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 回呼,以便將用戶端的生命週期延長至收到回音回應為止,這很可能是在頂層回呼傳回之後。
管道化用戶端
雖然必須先建立一對端點,但管道化程式碼簡單許多:
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;
}
與用戶端教學課程不同,非同步迴圈會執行一次,同時執行非管道化和管道化程式碼,以觀察作業順序。用戶端會追蹤收到的回應數量,以便在預期不會再收到伺服器傳送的訊息時,終止迴圈。
建構用戶端
視需要建構用戶端,確認一切正常:
設定 GN 建構作業,加入伺服器:
fx set core.x64 --with //examples/fidl/cpp/request_pipelining/client:echo-client建構 Fuchsia 映像檔:
fx build
執行範例程式碼
本教學課程提供
<0x0Afuchsia.examples.Echofuchsia.examples.EchoLauncher
設定建構作業,以便納入提供的套件,其中包含 echo 領域、伺服器和用戶端:
fx set core.x64 --with //examples/fidl/cpp/request_pipelining建構 Fuchsia 映像檔:
fx build執行
echo_realm元件。這會建立用戶端和伺服器元件例項,並將功能路徑導向:ffx component run /core/ffx-laboratory:echo_realm fuchsia-pkg://fuchsia.com/echo-launcher-cpp#meta/echo_realm.cm啟動
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!
根據列印順序,您可以看到管道化案例的速度較快。即使先傳送非管道化要求,管道化案例的回應也會先抵達,因為要求管道化可節省用戶端與伺服器之間的往返行程。要求管道化也會簡化程式碼。
如要進一步瞭解通訊協定要求管道,包括如何處理可能失敗的通訊協定要求,請參閱 FIDL API 評量標準。
終止領域元件,停止執行作業並清除元件例項:
ffx component destroy /core/ffx-laboratory:echo_realm