-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerApplication.cc
101 lines (77 loc) · 2.64 KB
/
ServerApplication.cc
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
#include "ServerApplication.h"
#include <iostream>
#include "Server.h"
#include "Ranking.h"
#include "ClientInterface.h"
using namespace std;
using namespace TP1;
Server* Server::_serverInstance = NULL;
int ServerApplication::runApp(int argc, char** argv) {
//Local and helper variables
int curClient = 0;
string clientMessage = "";
string position = "";
string port = argv[1];
bool isValid = false, isClosingMessage = false;
if (LOGGING) {
cout << "Starting server!" << endl;
cout << "Number of arguments: " << argc << endl;
cout << "Press ctrl + c at anytime to exit" << endl;
}
Server* server = Server::getInstance();
//Sets up server configuration and structures
server->setUp(port);
//initializes structure to handle race times
_timeRanking = new Ranking();
//Server's main loop
while (true) {
//Below calls are blocking, will wait until
//Client connects and send their time in the race
curClient = server->acceptClient();
do {
clientMessage = server->getMessageFromClient(curClient);
isValid = isValidMessage(clientMessage);
//First, we'll check if client sends a valid message
if (!isValid) {
server->sendMessageToClient(curClient, "0");
isClosingMessage = false; //We'll keep taking request from user
continue;
}
//Checks if client wants to close connection
isClosingMessage = isClosingSignal(clientMessage);
if (isClosingMessage) {
_timeRanking->clear();
server->closeConnection(curClient);
} else {
//Will handle user request, sending his/her
//position back
position = _timeRanking->insert(clientMessage);
cout << position << endl;
server->sendMessageToClient(curClient, position);
}
} while (!isClosingMessage);
}
//Will never reach below lines in single-threaded version
server->stop();
return 0;
}
/**
* A closing signal is a negative number which the client sends
**/
bool ServerApplication::isClosingSignal(string message) {
int signal = stoi(message);
if (signal < 0)
return true;
else
return false;
}
/**
* A valid message is a message which starts with a digit
**/
bool ServerApplication::isValidMessage(string message) {
return strtoll(message.c_str(), NULL, 10);
}
ServerApplication::~ServerApplication() {
Server::deleteInstance();
if (!_timeRanking) delete(_timeRanking);
}