C++版gRPCのクライアントのメモ。
サーバーのprotoファイルと同じものを使用する。
#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