libcopp  2.2.0
client-main.cpp
Go to the documentation of this file.
1 // Copyright 2022 atframework
2 
3 #include <grpcpp/grpcpp.h>
4 
5 #include <iostream>
6 #include <memory>
7 #include <string>
8 
9 #include "helloworld.grpc.pb.h"
10 
11 using grpc::Channel;
12 using grpc::ClientContext;
13 using grpc::Status;
14 using helloworld::Greeter;
15 using helloworld::HelloReply;
16 using helloworld::HelloRequest;
17 
19  public:
20  explicit GreeterClient(std::shared_ptr<Channel> channel) : stub_(Greeter::NewStub(channel)) {}
21 
22  // Assembles the client's payload, sends it and presents the response back
23  // from the server.
24  std::string SayHello(const std::string& user) {
25  // Data we are sending to the server.
26  HelloRequest request;
27  request.set_name(user);
28 
29  // Container for the data we expect from the server.
30  HelloReply reply;
31 
32  // Context for the client. It could be used to convey extra information to
33  // the server and/or tweak certain RPC behaviors.
34  ClientContext context;
35 
36  // The actual RPC.
37  Status status = stub_->SayHello(&context, request, &reply);
38 
39  // Act upon its status.
40  if (status.ok()) {
41  return reply.message();
42  } else {
43  std::cout << status.error_code() << ": " << status.error_message() << std::endl;
44  return "RPC failed";
45  }
46  }
47 
48  private:
49  std::unique_ptr<Greeter::Stub> stub_;
50 };
51 
52 int main(int argc, char** argv) {
53  // Instantiate the client. It requires a channel, out of which the actual RPCs
54  // are created. This channel models a connection to an endpoint specified by
55  // the argument "--target=" which is the only expected argument.
56  // We indicate that the channel isn't authenticated (use of
57  // InsecureChannelCredentials()).
58  std::string target_str;
59  std::string arg_str("--target");
60  if (argc > 1) {
61  std::string arg_val = argv[1];
62  size_t start_pos = arg_val.find(arg_str);
63  if (start_pos != std::string::npos) {
64  start_pos += arg_str.size();
65  if (arg_val[start_pos] == '=') {
66  target_str = arg_val.substr(start_pos + 1);
67  } else {
68  std::cout << "The only correct argument syntax is --target=" << std::endl;
69  return 0;
70  }
71  } else {
72  std::cout << "The only acceptable argument is --target=" << std::endl;
73  return 0;
74  }
75  } else {
76  target_str = "localhost:50051";
77  }
78  GreeterClient greeter(grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
79  std::string user("world");
80  std::string reply = greeter.SayHello(user);
81  std::cout << "Greeter received: " << reply << std::endl;
82 
83  return 0;
84 }
std::unique_ptr< Greeter::Stub > stub_
Definition: client-main.cpp:49
std::string SayHello(const std::string &user)
Definition: client-main.cpp:24
GreeterClient(std::shared_ptr< Channel > channel)
Definition: client-main.cpp:20
int main(int argc, char **argv)
Definition: client-main.cpp:52