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