-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadbalancer.cpp
82 lines (62 loc) · 2.37 KB
/
loadbalancer.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
82
#include <thread>
#include <vector>
#include <chrono>
#include <iostream>
#include "loadbalancer.h"
#include "autocompleteprotocol.h"
LoadBalancer::LoadBalancer(const std::vector<std::pair<std::string, int>> &servers) :
serverAddresses_(servers),
nextServer_(0)
{
}
void HandleClient(ConnectionPeer clientPeer, ConnectionPeer serverPeer, std::mutex &outputMutex)
{
bool close = false;
size_t messageLength = 0;
while (!close) {
while ((messageLength = MessageLength(clientPeer.peek())) == 0)
std::this_thread::yield();
std::chrono::system_clock::time_point before = std::chrono::system_clock::now();
std::string message = clientPeer.read(messageLength);
serverPeer.write(message);
close = (DecodeQuery(message).size() == 0);
outputMutex.lock();
std::cout << "S_LB "
<< std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now() - before).count()
<< '\n';
outputMutex.unlock();
if (!close) {
while ((messageLength = MessageLength(serverPeer.peek())) == 0)
std::this_thread::yield();
before = std::chrono::system_clock::now();
message = serverPeer.read(messageLength);
clientPeer.write(message);
outputMutex.lock();
std::cout << "S_LB "
<< std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now() - before).count()
<< '\n';
outputMutex.unlock();
}
}
clientPeer.close();
serverPeer.close();
}
void LoadBalancer::run(int port, int maxClients)
{
ConnectionPeer loadBalancingServer;
std::mutex outputMutex;
loadBalancingServer.listen(port);
while (maxClients--) {
ConnectionPeer nextClient = loadBalancingServer.acceptClient();
ConnectionPeer nextServerConnection;
nextServerConnection.connect(serverAddresses_[nextServer_].first,
serverAddresses_[nextServer_].second);
std::thread clientHandler(HandleClient, nextClient, nextServerConnection,
std::ref(outputMutex));
clientHandler.detach();
nextServer_ = (nextServer_ + 1) % serverAddresses_.size();
}
loadBalancingServer.close();
}