-
Notifications
You must be signed in to change notification settings - Fork 0
/
greeter_async_server.cc
243 lines (216 loc) · 6.28 KB
/
greeter_async_server.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#include "helloworld.pb.h"
#include <cstdio>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/server.h>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <unistd.h>
#include <grpc/support/log.h>
#include <grpcpp/grpcpp.h>
#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif
using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerCompletionQueue;
using grpc::ServerContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class ServerImpl final {
public:
~ServerImpl() {}
void Shutdown() {
server_->Shutdown();
// Always shutdown the completion queue after the server.
cq_->Shutdown();
}
// There is no shutdown handling in this code.
void Run() {
std::string server_address("0.0.0.0:50051");
ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// Register "service_" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *asynchronous* service.
builder.RegisterService(&service_);
// Get hold of the completion queue used for the asynchronous communication
// with the gRPC runtime.
cq_ = builder.AddCompletionQueue();
// Finally assemble the server.
server_ = builder.BuildAndStart();
std::cout << "Server listening on " << server_address << std::endl;
// Proceed to the server's main loop.
std::vector<std::thread> threads;
for(int i=0;i<5;i++){
threads.emplace_back([this]() { HandleRpcs(); });
}
for(auto &t:threads){
t.join();
}
}
void create_new_rpc() {
auto ptr = std::make_shared<CallData>(&service_, cq_.get(), this);
calls.insert({ptr.get(), ptr});
}
private:
static constexpr int CONNECT = 0, READ = 1, WRITE = 2, FINISH = 3, DONE = 4;
class CallData;
struct Event {
Event(CallData *cd, int event) : cd(cd), event(event) {}
void Process(bool ok) { cd->Proceed(event, ok); };
CallData *cd;
int event;
bool pending = false;
};
class CallData {
public:
CallData(Greeter::AsyncService *service, ServerCompletionQueue *cq,
ServerImpl *server)
: service_(service), cq_(cq), server(server) {
stream =
new grpc::ServerAsyncReaderWriter<::helloworld::HelloReply,
::helloworld::HelloRequest>(&ctx_);
ctx_.AsyncNotifyWhenDone(&doneevent);
service_->RequestSayHello(&ctx_, stream, cq_, cq_, &connectevent);
}
void Proceed(int status_, bool ok) {
switch (status_) {
case CONNECT:
server->create_new_rpc();
stream->Read(&request_, &readevent);
break;
case READ:
if (ok) {
std::cout << request_.name() << std::endl;
stream->Read(&request_, &readevent);
} else {
// ok false means stream writedone in peer, so begin reply
std::cout << "Read done" << std::endl;
reply("reply1");
reply("reply2");
reply("reply3");
reply("reply4");
finish();
}
break;
case WRITE:
writeevent.pending=false;
if (!ok) {
_onwriteerror();
}else{
_onwrite();
}
break;
case DONE:
// client normally finish or canceled
if(ctx_.IsCancelled()){
std::cout << "Call canceled: " << std::endl;
}
break;
default:
if(status_ != FINISH){
std::cout << "RPC Finish status"<< status_ << "ok?" << ok << std::endl;
}
server->remove_finished_rpc(this);
}
}
void reply(std::string msg) {
std::unique_ptr<HelloReply> replymsg(new HelloReply);
replymsg->set_message(msg);
{
std::lock_guard<std::mutex> lk(mutex_queue);
send_queue.emplace(std::move(replymsg));
}
// invoke in case no tag in cq
_onwrite();
}
void finish() {
{
std::lock_guard<std::mutex> lk(mutex_queue);
send_queue.emplace(nullptr);
}
// invoke in case no tag in cq
_onwrite();
}
private:
void _onwrite() {
std::lock_guard<std::mutex> lk(mutex_write);
std::unique_ptr<HelloReply> reply;
{
std::lock_guard<std::mutex> lk(mutex_queue);
if (send_queue.empty() || writeevent.pending || finishevent.pending) {
return;
}
reply = std::move(send_queue.front());
send_queue.pop();
}
if (reply) {
writeevent.pending = true;
stream->Write(*reply, &writeevent);
} else {
finishevent.pending = true;
stream->Finish(Status::OK, &finishevent);
}
}
void _onwriteerror() {}
void _onreaderror() {}
private:
Greeter::AsyncService *service_;
ServerCompletionQueue *cq_;
ServerContext ctx_;
grpc::ServerAsyncReaderWriter<::helloworld::HelloReply,
::helloworld::HelloRequest> *stream;
HelloRequest request_;
int serverwrite3times = 0;
ServerImpl *server;
std::mutex mutex_write;
std::mutex mutex_queue;
std::queue<std::unique_ptr<HelloReply>> send_queue;
// events
Event connectevent{this, CONNECT};
Event readevent{this, READ};
Event writeevent{this, WRITE};
Event finishevent{this, FINISH};
Event doneevent{this, DONE};
};
private:
void HandleRpcs() {
create_new_rpc();
void *tag; // uniquely identifies a request.
bool ok;
while (true) {
// Next return if there's an event or when Shutdown
GPR_ASSERT(cq_->Next(&tag, &ok));
static_cast<Event *>(tag)->Process(ok);
}
}
void remove_finished_rpc(CallData *p) {
if (calls.find(p) == calls.end()) {
std::cout << "Not find rpc" << std::endl;
return;
}
calls.erase(p);
}
std::unique_ptr<ServerCompletionQueue> cq_;
Greeter::AsyncService service_;
std::unique_ptr<Server> server_;
std::map<CallData *, std::shared_ptr<CallData>> calls;
};
int main(int argc, char **argv) {
ServerImpl server;
server.Run();
std::thread t1([&server]() {
sleep(6000);
server.Shutdown();
});
return 0;
}