-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyTestClientHandler.cpp
55 lines (42 loc) · 1.62 KB
/
MyTestClientHandler.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
#include "MyTestClientHandler.h"
void MyTestClientHandler::handleClient(int socketfd) {
/* Read from server line by line until isEndReached is false ("end" line reached). */
bool isEndReached = true;
string current;
char buffer[1024];
int n;
while (isEndReached) {
/* Read current line. */
bzero(buffer, 1024);
n = (int)read(socketfd, buffer, 1023);
current = buffer;
if (n < 0) {
//perror("ERROR reading from socket");
exit(1);
}
if (current == "end" || current == "end\n" || current == "end\r\n") {
/* Reading should end. */
isEndReached = false;
} else {
bool isSolution = cacheManager->isSolutionExists(current);
string solution;
/* If there's a solution for the current string, get it and write it to the client.
* Else, use solver, save the solution at cacheManager and write it to the client. */
if (isSolution) {
solution = cacheManager->getSolution(current);
} else {
solution = solver->solveProblem(current);
cacheManager->saveSolution(current, solution);
}
/* Write solution to the client.
* Flush is used so that the output will be flushed instantly - changes will be written to
* memory. */
n = write(socketfd, solution.c_str(), (int)(solution.length()));
if (n < 0) {
//perror("ERROR writing to socket");
exit(1);
}
}
}
//close(socketfd);
}