-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.h
95 lines (75 loc) · 1.86 KB
/
Server.h
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
/*
* Server.h
*
* Created on: Dec 13, 2020
* Author: Eli
*/
#ifndef SERVER_H_
#define SERVER_H_
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include "commands.h"
#include "CLI.h"
using namespace std;
// ClientHandler interface
class ClientHandler {
public:
virtual void handle(int clientID) = 0;
};
//socketDIO for reading and writing from and into sockets
class socketDIO : public DefaultIO {
int socketFD;
public:
//constructor of socketDIO getting fileDescriptor
socketDIO(int fd) {
this->socketFD = fd;
}
void write(string text) override {
const char *charText = text.c_str();
send(socketFD, charText, text.size(), 0);
}
void write(float f) override {
char charText[sizeof(f) + 1];
sprintf(charText, "%f", f);
send(socketFD, charText, sizeof(charText), 0);
}
string read() override {
string serverInput = "";
char c = 0;
recv(socketFD, &c, sizeof(char), 0);
while (c != '\n') {
serverInput += c;
recv(socketFD, &c, sizeof(char), 0);
}
return serverInput;
}
void read(float *f) override {
recv(socketFD, f, sizeof(*f), 0);
}
};
// AnomalyDetectionHandler class - handle Client
class AnomalyDetectionHandler : public ClientHandler {
public:
virtual void handle(int clientID) {
socketDIO dio(clientID);
CLI cli(&dio);
cli.start();
}
};
class Server {
// the thread to run the start() method in
thread *t;
public:
int fileDescriptor;
struct sockaddr_in server, client;
bool acceptConnection;
Server(int port) throw(const char *);
virtual ~Server();
void start(ClientHandler &ch) throw(const char *);
void stop();
};
#endif /* SERVER_H_ */