マジック8ボール

Qt gRPCクライアントとC++gRPC

Magic 8 Ballはサーバに質問を送信し、受信した答えを表示します:

"Magic 8 ball example screenshot"

サンプルコードには以下のコンポーネントが含まれています:

  • magic8ball qt_add_protobuf()およびqt_add_grpc()CMake 関数を使用してメッセージとサービスを生成する Qt クライアントアプリケーション。gRPC
  • 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 チャネルオプションで指定されたポート50051localhost に接続します:

    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 は、クライアントが呼び出す メソッドです。リクエストオブジェクト、終了コールバック関数、エラーコールバック関数、 オブジェクトの4つのパラメータを持ちます。gRPC GrpcCallOptions

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();
    };

応答を受信すると、クライアント・アプリケーションは答えを表示します。

プロジェクト例 @ code.qt.io

© 2025 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.