-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.cpp
81 lines (64 loc) · 2.02 KB
/
server.cpp
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
#include <memory>
#include <iostream>
#include <thread>
#include "grpcCallData/HillClimberFI/HCInitTransaction.h"
#include "grpcCallData/HillClimberFI/HCFitnessTransaction.h"
#include "grpcCallData/HillClimberFI/HCStopTransaction.h"
#define BDD "api"
using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCompletionQueue;
using grpc::Status;
using hcfi::InitTransactionRequest;
using hcfi::FitnessResponse;
using hcfi::HillClimberService;
class ServerImpl final {
public:
ServerImpl() {
mongocxx::instance inst{};
conn = mongocxx::uri("mongodb://127.0.0.1:27017");
db = conn[BDD];
}
~ServerImpl() {
server_->Shutdown();
cq_->Shutdown();
}
void run() {
std::string server_address("0.0.0.0:50051");
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service_);
cq_ = builder.AddCompletionQueue();
server_ = builder.BuildAndStart();
std::cout << "Server listening on " << server_address << std::endl;
handleRpcs();
}
private:
// This can be run in multiple threads if needed.
void handleRpcs() {
// Spawn a all new CallData instances to serve new clients.
// HillClimberFI CallData instances
new HCInitTransaction(&service_, cq_.get(), db);
new HCFitnessTransaction(&service_, cq_.get(), db);
new HCStopTransaction(&service_, cq_.get(), db);
void* tag;
bool ok;
while (true) {
GPR_ASSERT(cq_->Next(&tag, &ok));
GPR_ASSERT(ok);
static_cast<CallData*>(tag)->proceed();
}
}
std::unique_ptr<ServerCompletionQueue> cq_;
HillClimberService::AsyncService service_;
std::unique_ptr<Server> server_;
mongocxx::client conn;
mongocxx::database db;
};
int main(int argc, char** argv) {
ServerImpl server;
server.run();
return 0;
}