-
Notifications
You must be signed in to change notification settings - Fork 0
/
CalculatorClient.cc
99 lines (86 loc) · 2.74 KB
/
CalculatorClient.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* CalculatorClient.cc
*
* Created on: Jul 8, 2018
* Author: prateek
*/
#include <iostream>
#include <grpcpp/grpcpp.h>
#include "calculator.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using calculator::InputNumber;
using calculator::OutputNumber;
using calculator::Calculator;
using namespace std;
class CalculatorClient
{
public:
CalculatorClient(shared_ptr<Channel> channel)
: stub_(Calculator::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
int doCalculate(int n1, int n2, const char* opr) {
// Data we are sending to the server.
Status status;
InputNumber request;
request.set_num1(n1);
request.set_num2(n2);
// Container for the data we expect from the server.
OutputNumber reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
if ( memcmp(opr,"add",3) == 0 )
{
status = stub_->Addition(&context, request, &reply);
}
else if ( memcmp(opr,"sub",3) == 0 )
{
status = stub_->Subraction(&context, request, &reply);
}
else if ( memcmp(opr,"mul",3) == 0 )
{
status = stub_->Multiply(&context, request, &reply);
}
else if ( memcmp(opr,"div",3) == 0 )
{
status = stub_->Divide(&context, request, &reply);
}
// Act upon its status.
if (status.ok())
{
return (int) reply.num();
}
else
{
cout << status.error_code() << ": " << status.error_message()
<< endl;
cout << "RPC failed";
return -1;
}
}
private:
std::unique_ptr<Calculator::Stub> stub_;
};
int main(int argc, char** argv) {
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
CalculatorClient calculate(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));
int n1 = 100, n2=10;
cout << "-------------- GRPC Calculator Client -------------"<<endl;
cout<<"num1: "<<n1<<" num2: "<<n2<<endl;
int reply = calculate.doCalculate(n1,n2,"add");
cout << "Calculator addition received : " << reply << endl;
reply = calculate.doCalculate(n1,n2,"sub");
cout << "Calculator subrcation received : " << reply << endl;
reply = calculate.doCalculate(n1,n2,"mul");
cout << "Calculator multiplication received: " << reply << endl;
reply = calculate.doCalculate(n1,n2,"div");
cout << "Calculator divison received: " << reply << endl;
return 0;
}