1 #include "greeter.grpc.fb.h"
2 #include "greeter_generated.h"
3
4 #include <grpc++/grpc++.h>
5
6 #include <iostream>
7 #include <memory>
8 #include <string>
9
10 class GreeterClient {
11 public:
GreeterClient(std::shared_ptr<grpc::Channel> channel)12 GreeterClient(std::shared_ptr<grpc::Channel> channel)
13 : stub_(Greeter::NewStub(channel)) {}
14
SayHello(const std::string & name)15 std::string SayHello(const std::string &name) {
16 flatbuffers::grpc::MessageBuilder mb;
17 auto name_offset = mb.CreateString(name);
18 auto request_offset = CreateHelloRequest(mb, name_offset);
19 mb.Finish(request_offset);
20 auto request_msg = mb.ReleaseMessage<HelloRequest>();
21
22 flatbuffers::grpc::Message<HelloReply> response_msg;
23
24 grpc::ClientContext context;
25
26 auto status = stub_->SayHello(&context, request_msg, &response_msg);
27 if (status.ok()) {
28 const HelloReply *response = response_msg.GetRoot();
29 return response->message()->str();
30 } else {
31 std::cerr << status.error_code() << ": " << status.error_message()
32 << std::endl;
33 return "RPC failed";
34 }
35 }
36
SayManyHellos(const std::string & name,int num_greetings,std::function<void (const std::string &)> callback)37 void SayManyHellos(const std::string &name, int num_greetings,
38 std::function<void(const std::string &)> callback) {
39 flatbuffers::grpc::MessageBuilder mb;
40 auto name_offset = mb.CreateString(name);
41 auto request_offset =
42 CreateManyHellosRequest(mb, name_offset, num_greetings);
43 mb.Finish(request_offset);
44 auto request_msg = mb.ReleaseMessage<ManyHellosRequest>();
45
46 flatbuffers::grpc::Message<HelloReply> response_msg;
47
48 grpc::ClientContext context;
49
50 auto stream = stub_->SayManyHellos(&context, request_msg);
51 while (stream->Read(&response_msg)) {
52 const HelloReply *response = response_msg.GetRoot();
53 callback(response->message()->str());
54 }
55 auto status = stream->Finish();
56 if (!status.ok()) {
57 std::cerr << status.error_code() << ": " << status.error_message()
58 << std::endl;
59 callback("RPC failed");
60 }
61 }
62
63 private:
64 std::unique_ptr<Greeter::Stub> stub_;
65 };
66
main(int argc,char ** argv)67 int main(int argc, char **argv) {
68 std::string server_address("localhost:50051");
69
70 auto channel =
71 grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials());
72 GreeterClient greeter(channel);
73
74 std::string name("world");
75
76 std::string message = greeter.SayHello(name);
77 std::cerr << "Greeter received: " << message << std::endl;
78
79 int num_greetings = 10;
80 greeter.SayManyHellos(name, num_greetings, [](const std::string &message) {
81 std::cerr << "Greeter received: " << message << std::endl;
82 });
83
84 return 0;
85 }
86