-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_client.cpp
More file actions
125 lines (91 loc) · 2.73 KB
/
Copy pathmain_client.cpp
File metadata and controls
125 lines (91 loc) · 2.73 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "dataexchange.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using grpc::ClientReader;
// grpc client
class DataExchangeClient
{
public:
DataExchangeClient(std::shared_ptr<Channel> channel)
: stub_(DataExchange::NewStub(channel))
{
}
int ReceiveNumber()
{
Empty request;
NumberReply reply;
ClientContext context;
Status status = stub_->GetNumber(&context, request, &reply);
if (status.ok())
return reply.value();
throw std::runtime_error("server error");
}
std::string ReceiveString()
{
Empty request;
StringReply reply;
ClientContext context;
Status status = stub_->GetString(&context, request, &reply);
if (status.ok())
return reply.value();
throw std::runtime_error("server error");
}
size_t ReceiveFile(const std::string& filename)
{
ClientContext context;
Empty empty;
std::unique_ptr<grpc::ClientReader<PartReply> > reader(
stub_->GetFile(&context, empty));
PartReply part;
std::ofstream fon;
fon.open(filename, std::ofstream::binary);
size_t cnt = 0;
while (reader->Read(&part))
{
cnt += part.value().size();
fon << part.value();
}
fon.close();
Status status = reader->Finish();
if (status.ok())
{
return cnt;
}
throw std::runtime_error("server error");
}
private:
std::unique_ptr<DataExchange::Stub> stub_;
};
int main(int argc, char** argv)
{
// TODO: add better param parsing
std::string param_message = "usage: main_client network_address[string] file_to_receive[string]";
if (argc != 3)
{
std::cout << param_message << std::endl;
return 1;
}
try
{
std::string net_addr = argv[1];
std::string filename = argv[2];
DataExchangeClient client(grpc::CreateChannel(net_addr, grpc::InsecureChannelCredentials()));
std::cout << "Client connected :" << net_addr << std::endl;
std::cout << "Number received :" << client.ReceiveNumber() << std::endl;
std::cout << "String received :" << client.ReceiveString() << std::endl;
std::cout << "File received with size :" << client.ReceiveFile(filename) << std::endl;
}
catch (std::exception const& e)
{
std::cout << std::endl << "Exception: " << e.what() << std::endl;
std::cout << param_message << std::endl;
return 1;
}
return 0;
}