-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverA.cpp
More file actions
372 lines (328 loc) · 11.7 KB
/
serverA.cpp
File metadata and controls
372 lines (328 loc) · 11.7 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
Author: Rajnandini Thopte
serverA.cpp
This code is for backend server A. It has access to all the usernames and their availabilities that are present in a.txt.
It stores and parses the information, sends usernames to client and also finds the common time availability for users present in its database
and sends it to the main server for further processing.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <algorithm>
#define SERVER_A 21463
#define SERVER_M 23463
#define BUFFER_SIZE 10000
#define LOCALHOST "127.0.0.1"
#define FAIL -1
using namespace std;
int serverA_sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in serverM_addr;
vector<string> map_checklist;
// Define map as a global variable
map<string, vector<pair<int, int>>> databaseA_map;
// Repurposed from Beej’s socket programming tutorial
// Creates the UDP socket for ServerA
void create_serverA_socket()
{
serverA_sockfd = socket(AF_INET, SOCK_DGRAM, 0); // creates a UDP socket
if (serverA_sockfd == FAIL)
{
perror("[ERROR] Server A cannot open socket.");
exit(1);
}
}
// Repurposed from Beej’s socket programming tutorial
// initializeConnection() sets the struct sockaddr_in for serverA with appropriate parameters and its' assigned UDP port number.
void initializeConnectionA()
{
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr(LOCALHOST);
my_addr.sin_port = htons(SERVER_A);
}
// Repurposed from Beej’s socket programming tutorial
void initializeConnectionM()
{
memset(&serverM_addr, 0, sizeof(serverM_addr));
serverM_addr.sin_family = AF_INET;
serverM_addr.sin_addr.s_addr = inet_addr(LOCALHOST);
serverM_addr.sin_port = htons(SERVER_M);
}
// Repurposed from Beej’s socket programming tutorial
void bindSocket()
{
// Bind the socket to the receive address
if (::bind(serverA_sockfd, (sockaddr *)&my_addr, sizeof(my_addr)) == -1)
{
perror("[ERROR] Server A failed to bind UDP socket.");
exit(1);
}
cout << "Server A is up and running using UDP on port " << SERVER_A <<"."<< endl;
}
// Custom function to convert a string to an integer
int strToInt(const string &str)
{
int res = 0;
for (char c : str)
{
res = res * 10 + (c - '0');
}
return res;
}
//This function reads input file a.txt and parses it into a map data structure with usernames as keys and time availabilities as values.
vector<string> readInput()
{
vector<string> usernames;
// Open the input file
ifstream input_file("a.txt");
// Check if the file is opened successfully
if (!input_file)
{
cerr << "Error: Could not open the input file" << endl;
return usernames;
}
// Read the file line by line
string line;
while (getline(input_file, line))
{
if (line.length() == 0)
{
continue;
}
// Split the line by semicolon
size_t pos = line.find(';');
string name = line.substr(0, pos);
string intervals = line.substr(pos + 2);
name.erase(std::remove(name.begin(), name.end(), ' '), name.end());
usernames.push_back(name);
// Split the ranges string by comma and brackets
vector<pair<int, int>> ranges;
pos = 0;
while ((pos = intervals.find('[', pos)) != string::npos)
{
size_t end_pos = intervals.find(']', pos);
string range_str = intervals.substr(pos + 1, end_pos - pos - 1);
pos = end_pos + 1;
// Split the range string by comma Eg- finding the comma between 5 and 6 ie 5, 6
size_t comma_pos = range_str.find(',');
//We use strToInt function because currently we have a string and we want to store values as a integer
int start = strToInt(range_str.substr(0, comma_pos));
int end = strToInt(range_str.substr(comma_pos + 1));
ranges.push_back(make_pair(start, end));
}
// Add the data to the map
databaseA_map[name] = ranges;
}
// Close the input file
input_file.close();
return usernames;
}
//Parsing the data received from Main server in Phase 2
void split_buffer(string buffer_phase2)
{
// Split the buffer by spaces
stringstream ss(buffer_phase2);
string name_check;
while (getline(ss, name_check, ' '))
{
map_checklist.push_back(name_check);
}
}
//This is the algorithm that calculates the common time availability among multiple users.
vector<pair<int, int>> CommonTimeAvailability(vector<pair<int, int>> intervals1, vector<pair<int, int>> intervals2)
{
vector<pair<int, int>> commonIntervals;
int i = 0, j = 0;
while (i < intervals1.size() && j < intervals2.size())
{
// check if the intervals overlap
if (intervals1[i].second < intervals2[j].first)
{
i++;
}
else if (intervals2[j].second < intervals1[i].first)
{
j++;
}
else
{
int start = max(intervals1[i].first, intervals2[j].first);
int end = min(intervals1[i].second, intervals2[j].second);
if (start < end) // check if it is a valid interval
{
commonIntervals.emplace_back(start, end);
}
if (intervals1[i].second < intervals2[j].second)
{
i++;
}
else
{
j++;
}
}
}
return commonIntervals;
}
int main()
{
// Create UDP socket for server A
create_serverA_socket();
// Create sockaddr_in struct
initializeConnectionA();
initializeConnectionM();
bindSocket();
// Reading input file
vector<string> usernames = readInput();
string data;
for (string username : usernames)
{
data += username + ',';
}
//Sending usernames of a.txt to server M
socklen_t addr_len = sizeof(serverM_addr);
if (sendto(serverA_sockfd, (void *)data.c_str(), data.length(), 0, (struct sockaddr *)&serverM_addr, addr_len) == FAIL)
{
perror("Server A failed to send usernames to Server M");
exit(1);
}
cout << "Server A finished sending a list of usernames to Main Server." << endl;
cout << endl;
cout << endl;
//while loop for continuous requests
while (true)
{
map_checklist.clear();
char buffer_phase2[BUFFER_SIZE];
socklen_t addr_len = sizeof(serverM_addr);
//Receiving usernames from Main server for which we need to find common time intervals.
int bytes_received = recvfrom(serverA_sockfd, buffer_phase2, BUFFER_SIZE, 0, (struct sockaddr *)&serverM_addr, &addr_len);
if (bytes_received == FAIL)
{
perror("Server A did not receieve usernames from Main Server");
exit(1);
}
buffer_phase2[bytes_received] = '\0';
cout << "Server A received the usernames from Main Server using UDP over port " << SERVER_A <<"." << endl;
//Parsing the data received from Main server
split_buffer(buffer_phase2);
//Finding the time availabilities for usernames received from main server from map
vector<pair<string, vector<pair<int, int>>>> selected_users;
for (const auto &selected_name : map_checklist)
{
// Check if the username exists in the data map
if (databaseA_map.find(selected_name) != databaseA_map.end())
{
// If it does, add it to the selected_users vector
selected_users.push_back(make_pair(selected_name, databaseA_map[selected_name]));
}
else
{
// If it doesn't, print an error message
cerr << "Error: No data found for user " << selected_name << endl;
}
}
//Finding common time intersection for the usernames received from Main server.
vector<pair<int, int>> time_intersection;
if (selected_users.size() == 1)
{
// If there is only one user, return their time intervals directly
//cout << "Only one user selected: " << selected_users[0].first << endl;
time_intersection = selected_users[0].second;
}
else if (selected_users.size() > 1)
{
// If there are multiple users, find the common time intervals iteratively
// Start with the time intervals of the first user
time_intersection = selected_users[0].second;
for (int i = 1; i < selected_users.size(); i++)
{
// Find the common intervals between the previously found common intervals
// and the time intervals of the current user
time_intersection = CommonTimeAvailability(time_intersection, selected_users[i].second);
}
}
//Formatting the final time intersection
string intersection_str = "";
for (const auto &interval : time_intersection)
{
intersection_str += "[" + to_string(interval.first) + ", " + to_string(interval.second) + "] ";
}
if (time_intersection.empty())
{
intersection_str = "[]";
}
char intersection_arr[intersection_str.size() + 1];
strcpy(intersection_arr, intersection_str.c_str());
//Sending intersection result to Main server
int size = intersection_str.size();
char output_arr[size + 1];
strcpy(output_arr, intersection_str.c_str());
int num_bytes_sent = sendto(serverA_sockfd, output_arr, size, 0, (struct sockaddr *)&serverM_addr, sizeof(serverM_addr));
if (num_bytes_sent == -1)
{
perror("Error in sending data");
exit(EXIT_FAILURE);
}
//Formatting print statement
if (time_intersection.empty())
{
string intersection_result = "Found intersection result ";
intersection_result += "[] ";
intersection_result += "for ";
for (int i = 0; i < selected_users.size(); i++)
{
intersection_result += selected_users[i].first;
// If this is not the last selected user, add a comma and space
if (i < selected_users.size() - 1)
{
intersection_result += ",";
}
}
intersection_result += ".";
cout << intersection_result << endl;
}
else
{
string intersection_result = "Found intersection result ";
// Loop through each interval and add its string representation to the result string
for (const auto &interval : time_intersection)
{
intersection_result += "[" + to_string(interval.first) + ", " + to_string(interval.second) + "] ";
}
// Add the names of the selected users to the result string
intersection_result += "for ";
for (int i = 0; i < selected_users.size(); i++)
{
intersection_result += selected_users[i].first;
// If this is not the last selected user, add a comma and space
if (i < selected_users.size() - 1)
{
intersection_result += ",";
}
}
intersection_result += ".";
// Print the intersection result to the console
cout << intersection_result << endl;
}
cout << "Server A finished sending the response to Main Server." << endl;
cout << endl;
cout << endl;
}
return 0;
}