S-JIS[2024-11-24] 変更履歴

gRPC C++クライアント

C++版gRPCのクライアントのメモ。


protoファイル

サーバーのprotoファイルと同じものを使用する。


C++ソースファイル

src/Int64PairClient.cpp

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>
#include "example.grpc.pb.h"

example.protoビルドするとexample.grpc.pb.hというヘッダーファイルが作られるので、それをインクルードする。

using example::grpc::ExampleService;
using example::grpc::Int64PairRequest;
using example::grpc::Int64PairResponse;
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;

example.protoをビルドするとExampleService::Stubが作られるので、それを使って、リクエストを送信する関数を用意する。

class Int64PairClient
{
    public:
        Int64PairClient(std::shared_ptr<Channel> channel)
            : stub_(ExampleService::NewStub(channel)) {}

        int SendInt64Pair(Int64PairRequest &request, Int64PairResponse *response)
        {
            ClientContext context;

            Status status = stub_->SendInt64Pair(&context, request, response);

            if (status.ok())
            {
                return 0;
            }
            else
            {
                std::cerr << "gRPC error:" << status.error_code() << ": " << status.error_message() << std::endl;
                return status.error_code();
            }
    }

    private:
        std::unique_ptr<ExampleService::Stub> stub_;
};
int main(int argc, char **argv)
{
    int port = 50051;
    std::string address = "localhost:" + std::to_string(port);
    std::cout << "address = " << address << std::endl;

    Int64PairClient client(grpc::CreateChannel(address, grpc::InsecureChannelCredentials()));


    Int64PairRequest request;
    request.set_first_value(123);
    request.set_second_value(456);

    Int64PairResponse response;
    client.SendInt64Pair(request, &response);
    std::cout << "response: " << response.first_value() << ", " << response.second_value() << std::endl;


    return 0;
}

ビルド

cmakeとmakeを使ってビルドする。→C++版gRPCアプリケーションのビルド方法


実行

./Int64PairClient

リクエストを受け付けるC++版gRPCサーバーの例


gRPC C++へ戻る / gRPCへ戻る / 技術メモへ戻る
メールの送信先:ひしだま