マジック8ボール
Qt gRPC™ クライアントとC++製のgRPC サーバー間のHTTP/2接続の確立。
Magic 8 Ballはサーバーに質問を送信し、受け取った回答を表示します:

このサンプルコードには、以下のコンポーネントが含まれています:
magic8ballQt XML メッセージおよびサービスの Qt コード生成に、CMake 関数qt_add_protobuf()およびqt_add_grpc()を使用する QtgRPC クライアントアプリケーション。serverサーバーコードの生成と単純なサーバーロジックの実装のために、C++gRPC プラグインを呼び出すアプリケーション。
注: C++gRPC プラグインがインストールされている必要があります 。詳細はこちらをご覧ください:モジュールの前提条件
どちらのコンポーネントも、exampleservice.proto ファイルに記載された protobuf スキーマから生成されたメッセージを使用します:
syntax = "proto3";
package qtgrpc.examples;
message AnswerRequest {
string question = 1;
}
message AnswerResponse {
string message = 1;
}
service ExampleService {
rpc answerMethod(AnswerRequest) returns (AnswerResponse) {}
}gRPC クライアントはQMLオブジェクトとして定義されており、コードのコンパイル後に利用可能になります。
ExampleServiceClient {
id: grpcClient
channel: grpcChannel.channel
}クライアントサービスは、gRPC チャネルオプションで指定されているポート50051 を使用してlocalhost に接続します:
GrpcHttp2Channel {
id: grpcChannel
hostUri: "http://localhost:50051"
// Optionally, you can specify custom channel options here
// options: GrpcChannelOptions {}
}そして、サーバー側にリクエストを送信します:
function requestAnswer(question: string): void {
...
root.answerReq.question = question;
grpcClient.answerMethod(root.answerReq, finishCallback, errorCallback, grpcCallOptions);
}answerMethod は、クライアントが呼び出すgRPC のメソッドです。このメソッドには、リクエストオブジェクト、完了コールバック関数、エラーコールバック関数、およびGrpcCallOptions オブジェクトの4つのパラメータがあります。
「Ask 」ボタンをクリックして、magic8ballサーバーにリクエストを送信します。
注: サーバーはクライアントアプリケーションと並行して実行する必要があります 。
server アプリケーションは、回答リストからランダムに回答を選択し、そのデータをクライアントのポートに送信します。また、リクエストにquestion フィールドが含まれており、かつその値が空でないかどうかも確認します。このフィールドが空の場合、StatusCode::INVALID_ARGUMENT
grpc::Status answerMethod(grpc::ServerContext *, const AnswerRequest *request,
AnswerResponse *response) override
{
if (request->question().empty()) {
std::cerr << "Question is empty" << std::endl;
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Question is empty");
}
std::cout << "Received question: " << request->question() << std::endl;
response->set_message(getRandomAnswer());
return grpc::Status();
};レスポンスを受信すると、クライアントアプリケーションは回答を表示します。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.