-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cpp
212 lines (181 loc) · 5.66 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
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
#define NOMINMAX
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <thread>
#include <iostream>
#include <limits>
#include <chrono>
#include <streambuf>
#include <string>
#include <sstream>
#include <mutex>
#include <vector>
using namespace std;
// Display is not working right after 1699927628-1699931773 time with 3 clients
// try to break server with overflow
// fix numeric limts
class PriceAggregator : public streambuf {
private:
int high, low, close;
chrono::time_point<chrono::system_clock> start_time;
const int interval = 60; // 1 minute in seconds
mutex mtx;
void reset() {
high = numeric_limits<int>::min();
low = numeric_limits<int>::max();
close = 0;
}
protected:
// Process incoming trade data
int underflow() override {
string line;
if (getline(cin, line)) {
istringstream iss(line);
int price;
while (iss >> price) {
lock_guard<mutex> lock(mtx);
processTrade(price);
}
}
return traits_type::eof();
}
// Output aggregated data
int overflow(int c = traits_type::eof()) override {
lock_guard<mutex> lock(mtx);
emitBar(cout);
return c;
}
public:
PriceAggregator() {
reset();
start_time = chrono::system_clock::now();
}
void processTrade(int price) {
high = max(high, price);
low = min(low, price);
close = price;
}
void emitBar(ostream& bars_out) {
auto now = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = now - start_time;
if (elapsed_seconds.count() >= interval) {
bars_out << "{ \"start_time\": \"" << chrono::system_clock::to_time_t(start_time)
<< "\", \"high\": " << high << ", \"low\": " << low << ", \"close\": " << close << " }\n";
reset();
start_time = now;
}
}
};
#pragma comment(lib, "Ws2_32.lib")
#define PORT 8080
mutex aggregatorMutex;
void handleClient(SOCKET clientSocket, PriceAggregator& aggregator) {
char recvbuf[512];
int recvbuflen = 512;
int iResult;
// Process incoming data from client
while (true) {
iResult = recv(clientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
lock_guard<mutex> lock(aggregatorMutex);
// Process each received price
istringstream iss(string(recvbuf, iResult));
int price;
while (iss >> price) {
aggregator.processTrade(price);
}
} else if (iResult == 0) {
cout << "Connection closing...\n";
break;
} else {
cerr << "recv failed: " << WSAGetLastError() << '\n';
break;
}
}
closesocket(clientSocket);
}
void sendAggregatedData(SOCKET clientSocket, PriceAggregator& aggregator) {
while (true) {
this_thread::sleep_for(chrono::seconds(60)); // 60 seconds
lock_guard<mutex> lock(aggregatorMutex);
ostringstream oss;
aggregator.emitBar(oss);
string dataToSend = oss.str();
if (!dataToSend.empty()) {
int iSendResult = send(clientSocket, dataToSend.c_str(), dataToSend.length(), 0);
if (iSendResult == SOCKET_ERROR) {
cerr << "send failed: " << WSAGetLastError() << '\n';
closesocket(clientSocket);
break;
}
}
}
}
int main() {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
cerr << "WSAStartup failed: " << iResult << '\n';
return 1;
}
struct addrinfo *result = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL, to_string(PORT).c_str(), &hints, &result);
if (iResult != 0) {
cerr << "getaddrinfo failed: " << iResult << '\n';
WSACleanup();
return 1;
}
SOCKET ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
cerr << "socket failed: " << WSAGetLastError() << '\n';
freeaddrinfo(result);
WSACleanup();
return 1;
}
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
cerr << "bind failed: " << WSAGetLastError() << '\n';
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
cerr << "listen failed: " << WSAGetLastError() << '\n';
closesocket(ListenSocket);
WSACleanup();
return 1;
}
PriceAggregator aggregator;
vector<thread> clientThreads;
while (true) {
SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
cerr << "accept failed: " << WSAGetLastError() << '\n';
continue;
}
// Handle client in a separate thread
clientThreads.push_back(thread(handleClient, ClientSocket, ref(aggregator)));
// Another thread for sending aggregated data
clientThreads.push_back(thread(sendAggregatedData, ClientSocket, ref(aggregator)));
}
closesocket(ListenSocket);
// Join all threads
for (auto& thread : clientThreads) {
if (thread.joinable()) {
thread.join();
}
}
// Clean up Winsock
WSACleanup();
return 0;
}