2 #include <samchon/protocol/Server.hpp> 4 #include <unordered_set> 5 #include <samchon/library/RWMutex.hpp> 13 class CalculatorServer;
14 class CalculatorClient;
16 class CalculatorClient
17 :
public protocol::IProtocol
20 CalculatorServer *server;
21 std::shared_ptr<protocol::ClientDriver> driver;
27 CalculatorClient(CalculatorServer *server, std::shared_ptr<protocol::ClientDriver> driver)
29 this->server = server;
30 this->driver = driver;
32 virtual ~CalculatorClient() =
default;
37 virtual void sendData(std::shared_ptr<protocol::Invoke> invoke)
override 39 driver->sendData(invoke);
41 virtual void replyData(std::shared_ptr<protocol::Invoke> invoke)
override 43 if (invoke->getListener() ==
"computePlus")
45 double x = invoke->front()->getValue<
double>();
46 double y = invoke->front()->getValue<
double>();
50 else if (invoke->getListener() ==
"computeMinus")
52 double x = invoke->front()->getValue<
double>();
53 double y = invoke->front()->getValue<
double>();
58 ((protocol::IProtocol*)server)->replyData(invoke);
65 void computePlus(
double x,
double y)
67 sendData(std::make_shared<protocol::Invoke>(
"printPlus", x, y, x + y));
69 void computeMinus(
double x,
double y)
71 sendData(std::make_shared<protocol::Invoke>(
"printPlus", x, y, x - y));
75 class CalculatorServer
76 :
public protocol::Server,
77 public protocol::IProtocol
80 std::unordered_set<std::shared_ptr<CalculatorClient>> clients;
87 CalculatorServer() : protocol::Server()
90 virtual ~CalculatorServer() =
default;
93 void addClient(std::shared_ptr<protocol::ClientDriver> driver)
override 96 std::shared_ptr<CalculatorClient> client(
new CalculatorClient(
this, driver));
97 library::UniqueWriteLock uk(mtx);
99 clients.insert(client);
104 driver->listen(client.get());
108 clients.erase(client);
115 virtual void sendData(std::shared_ptr<protocol::Invoke> invoke)
117 std::vector<std::thread> threads;
118 library::UniqueReadLock uk(mtx);
120 threads.reserve(clients.size());
121 for (
auto it = clients.begin(); it != clients.end(); it++)
122 threads.emplace_back(&CalculatorClient::sendData, it->get());
126 for (
auto it = threads.begin(); it != threads.end(); it++)
129 virtual void replyData(std::shared_ptr<protocol::Invoke> invoke)
131 if (invoke->getListener() ==
"computeMultiply")
133 double x = invoke->front()->getValue<
double>();
134 double y = invoke->front()->getValue<
double>();
136 computeMultiply(x, y);
138 else if (invoke->getListener() ==
"computeDivide")
140 double x = invoke->front()->getValue<
double>();
141 double y = invoke->front()->getValue<
double>();
151 void computeMultiply(
double x,
double y)
153 sendData(std::make_shared<protocol::Invoke>(
"printMultiply", x, y, x * y));
155 void computeDivide(
double x,
double y)
157 sendData(std::make_shared<protocol::Invoke>(
"printDivide", x, y, x / y));
166 CalculatorServer server;
virtual void replyData(std::shared_ptr< Invoke >)=0
virtual void sendData(std::shared_ptr< Invoke >)=0