xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/keepalive/greeter_callback_client.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 /*
2  *
3  * Copyright 2021 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include <condition_variable>
20 #include <iostream>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 #include <thread>
25 
26 #include "absl/flags/flag.h"
27 #include "absl/flags/parse.h"
28 
29 #include <grpcpp/grpcpp.h>
30 
31 #ifdef BAZEL_BUILD
32 #include "examples/protos/helloworld.grpc.pb.h"
33 #else
34 #include "helloworld.grpc.pb.h"
35 #endif
36 
37 ABSL_FLAG(std::string, target, "localhost:50051", "Server address");
38 
39 using grpc::Channel;
40 using grpc::ClientContext;
41 using grpc::Status;
42 using helloworld::Greeter;
43 using helloworld::HelloReply;
44 using helloworld::HelloRequest;
45 
46 class GreeterClient {
47  public:
GreeterClient(std::shared_ptr<Channel> channel)48   GreeterClient(std::shared_ptr<Channel> channel)
49       : stub_(Greeter::NewStub(channel)) {}
50 
51   // Assembles the client's payload, sends it and presents the response back
52   // from the server.
SayHello(const std::string & user)53   std::string SayHello(const std::string& user) {
54     // Data we are sending to the server.
55     HelloRequest request;
56     request.set_name(user);
57 
58     // Container for the data we expect from the server.
59     HelloReply reply;
60 
61     // Context for the client. It could be used to convey extra information to
62     // the server and/or tweak certain RPC behaviors.
63     ClientContext context;
64 
65     // The actual RPC.
66     std::mutex mu;
67     std::condition_variable cv;
68     bool done = false;
69     Status status;
70     stub_->async()->SayHello(&context, &request, &reply,
71                              [&mu, &cv, &done, &status](Status s) {
72                                status = std::move(s);
73                                std::lock_guard<std::mutex> lock(mu);
74                                done = true;
75                                cv.notify_one();
76                              });
77 
78     std::unique_lock<std::mutex> lock(mu);
79     while (!done) {
80       cv.wait(lock);
81     }
82 
83     // Act upon its status.
84     if (status.ok()) {
85       return reply.message();
86     } else {
87       std::cout << status.error_code() << ": " << status.error_message()
88                 << std::endl;
89       return "RPC failed";
90     }
91   }
92 
93  private:
94   std::unique_ptr<Greeter::Stub> stub_;
95 };
96 
main(int argc,char ** argv)97 int main(int argc, char** argv) {
98   absl::ParseCommandLine(argc, argv);
99   // Instantiate the client. It requires a channel, out of which the actual RPCs
100   // are created. This channel models a connection to an endpoint specified by
101   // the argument "--target=" which is the only expected argument.
102   std::string target_str = absl::GetFlag(FLAGS_target);
103   grpc::ChannelArguments args;
104   // Sample way of setting keepalive arguments on the client channel. Here we
105   // are configuring a keepalive time period of 20 seconds, with a timeout of 10
106   // seconds. Additionally, pings will be sent even if there are no calls in
107   // flight on an active connection.
108   args.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, 20 * 1000 /*20 sec*/);
109   args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 10 * 1000 /*10 sec*/);
110   args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1);
111   for (auto i = 0; i < 10; ++i) {
112     GreeterClient greeter(grpc::CreateCustomChannel(
113         target_str, grpc::InsecureChannelCredentials(), args));
114     std::string user("world");
115     std::string reply = greeter.SayHello(user);
116     std::cout << "Greeter received: " << reply << std::endl;
117     std::this_thread::sleep_for(std::chrono::seconds(10));
118   }
119 
120   return 0;
121 }
122