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 "absl/flags/flag.h"
24 #include "absl/flags/parse.h"
25
26 #include <grpcpp/grpcpp.h>
27
28 #ifdef BAZEL_BUILD
29 #include "examples/protos/helloworld.grpc.pb.h"
30 #else
31 #include "helloworld.grpc.pb.h"
32 #endif
33
34 ABSL_FLAG(std::string, target, "localhost:50051", "Server address");
35
36 using grpc::Channel;
37 using grpc::ClientContext;
38 using grpc::Status;
39 using helloworld::Greeter;
40 using helloworld::HelloReply;
41 using helloworld::HelloRequest;
42
43 class GreeterClient {
44 public:
GreeterClient(std::shared_ptr<Channel> channel)45 GreeterClient(std::shared_ptr<Channel> channel)
46 : stub_(Greeter::NewStub(channel)) {}
47
48 // Assembles the client's payload, sends it and presents the response back
49 // from the server.
SayHello(const std::string & user)50 std::string SayHello(const std::string& user) {
51 // Data we are sending to the server.
52 HelloRequest request;
53 request.set_name(user);
54
55 // Container for the data we expect from the server.
56 HelloReply reply;
57
58 // Context for the client. It could be used to convey extra information to
59 // the server and/or tweak certain RPC behaviors.
60 ClientContext context;
61
62 // The actual RPC.
63 Status status = stub_->SayHello(&context, request, &reply);
64
65 // Act upon its status.
66 if (status.ok()) {
67 return reply.message();
68 } else {
69 std::cout << status.error_code() << ": " << status.error_message()
70 << std::endl;
71 return "RPC failed";
72 }
73 }
74
75 private:
76 std::unique_ptr<Greeter::Stub> stub_;
77 };
78
main(int argc,char ** argv)79 int main(int argc, char** argv) {
80 absl::ParseCommandLine(argc, argv);
81 // Instantiate the client. It requires a channel, out of which the actual RPCs
82 // are created. This channel models a connection to an endpoint specified by
83 // the argument "--target=" which is the only expected argument.
84 std::string target_str = absl::GetFlag(FLAGS_target);
85 // We indicate that the channel isn't authenticated (use of
86 // InsecureChannelCredentials()).
87 GreeterClient greeter(
88 grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
89 std::string user("world");
90 std::string reply = greeter.SayHello(user);
91 std::cout << "Greeter received: " << reply << std::endl;
92
93 return 0;
94 }
95