• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2015 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 <iostream>
20 #include <memory>
21 #include <string>
22 
23 #include <grpcpp/grpcpp.h>
24 #include <grpc/support/log.h>
25 #include <thread>
26 
27 #include "helloworld.grpc.pb.h"
28 
29 using grpc::Channel;
30 using grpc::ClientAsyncResponseReader;
31 using grpc::ClientContext;
32 using grpc::CompletionQueue;
33 using grpc::Status;
34 using helloworld::HelloRequest;
35 using helloworld::HelloReply;
36 using helloworld::Greeter;
37 
38 class GreeterClient {
39   public:
GreeterClient(std::shared_ptr<Channel> channel)40     explicit GreeterClient(std::shared_ptr<Channel> channel)
41             : stub_(Greeter::NewStub(channel)) {}
42 
43     // Assembles the client's payload and sends it to the server.
SayHello(const std::string & user)44     void SayHello(const std::string& user) {
45         // Data we are sending to the server.
46         HelloRequest request;
47         request.set_name(user);
48 
49         // Call object to store rpc data
50         AsyncClientCall* call = new AsyncClientCall;
51 
52         // stub_->PrepareAsyncSayHello() creates an RPC object, returning
53         // an instance to store in "call" but does not actually start the RPC
54         // Because we are using the asynchronous API, we need to hold on to
55         // the "call" instance in order to get updates on the ongoing RPC.
56         call->response_reader =
57             stub_->PrepareAsyncSayHello(&call->context, request, &cq_);
58 
59         // StartCall initiates the RPC call
60         call->response_reader->StartCall();
61 
62         // Request that, upon completion of the RPC, "reply" be updated with the
63         // server's response; "status" with the indication of whether the operation
64         // was successful. Tag the request with the memory address of the call object.
65         call->response_reader->Finish(&call->reply, &call->status, (void*)call);
66 
67     }
68 
69     // Loop while listening for completed responses.
70     // Prints out the response from the server.
AsyncCompleteRpc()71     void AsyncCompleteRpc() {
72         void* got_tag;
73         bool ok = false;
74 
75         // Block until the next result is available in the completion queue "cq".
76         while (cq_.Next(&got_tag, &ok)) {
77             // The tag in this example is the memory location of the call object
78             AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
79 
80             // Verify that the request was completed successfully. Note that "ok"
81             // corresponds solely to the request for updates introduced by Finish().
82             GPR_ASSERT(ok);
83 
84             if (call->status.ok())
85                 std::cout << "Greeter received: " << call->reply.message() << std::endl;
86             else
87                 std::cout << "RPC failed" << std::endl;
88 
89             // Once we're complete, deallocate the call object.
90             delete call;
91         }
92     }
93 
94   private:
95 
96     // struct for keeping state and data information
97     struct AsyncClientCall {
98         // Container for the data we expect from the server.
99         HelloReply reply;
100 
101         // Context for the client. It could be used to convey extra information to
102         // the server and/or tweak certain RPC behaviors.
103         ClientContext context;
104 
105         // Storage for the status of the RPC upon completion.
106         Status status;
107 
108 
109         std::unique_ptr<ClientAsyncResponseReader<HelloReply>> response_reader;
110     };
111 
112     // Out of the passed in Channel comes the stub, stored here, our view of the
113     // server's exposed services.
114     std::unique_ptr<Greeter::Stub> stub_;
115 
116     // The producer-consumer queue we use to communicate asynchronously with the
117     // gRPC runtime.
118     CompletionQueue cq_;
119 };
120 
main(int argc,char ** argv)121 int main(int argc, char** argv) {
122 
123 
124     // Instantiate the client. It requires a channel, out of which the actual RPCs
125     // are created. This channel models a connection to an endpoint (in this case,
126     // localhost at port 50051). We indicate that the channel isn't authenticated
127     // (use of InsecureChannelCredentials()).
128     GreeterClient greeter(grpc::CreateChannel(
129             "localhost:50051", grpc::InsecureChannelCredentials()));
130 
131     // Spawn reader thread that loops indefinitely
132     std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);
133 
134     for (int i = 0; i < 100; i++) {
135         std::string user("world " + std::to_string(i));
136         greeter.SayHello(user);  // The actual RPC call!
137     }
138 
139     std::cout << "Press control-c to quit" << std::endl << std::endl;
140     thread_.join();  //blocks forever
141 
142     return 0;
143 }
144