-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyParallelServer.cpp
More file actions
89 lines (67 loc) · 2.54 KB
/
MyParallelServer.cpp
File metadata and controls
89 lines (67 loc) · 2.54 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
//
// Created by ori on 17/01/2020.
//
#include "MyParallelServer.h"
int MyParallelServer::open(int port, ClientHandler *handler) {
//create socket
int socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (socketfd == -1) {
//error
std::cerr << "Could not create a socket" << std::endl;
return -1;
}
//bind socket to IP address
// we first need to create the sockaddr obj.
sockaddr_in address_; //in means IP4
address_.sin_family = AF_INET;
address_.sin_addr.s_addr = INADDR_ANY; //give me any IP allocated for my machine
address_.sin_port = htons(port);
//we need to convert our number
// to a number that the network understands.
//the actual bind command
if (bind(socketfd, (struct sockaddr *) &address_, sizeof(address_)) == -1) {
std::cerr << "Could not bind the socket to an IP" << std::endl;
return -2;
}
thread handle([this, socketfd, handler, address_] { start(socketfd, handler, address_); });
handle.join();
return 0;
}
//close the server in case we have got 10 clients or there were no connections to the server
void MyParallelServer::stop() {
cout << "Close the server..." << endl;
for (int j = 0; j < i; j++) {
client[j].join();
}
this->stop_server = true;
}
void MyParallelServer::start(int socketfd, ClientHandler *handler, sockaddr_in address_) {
while (!stop_server) {
if (listen(socketfd, 5) == -1) { //can also set to SOMAXCON (max connections)
std::cerr << "Error during listening command" << std::endl;
} else {
cout << "Server is now listening ...\n" << endl;
//time-out for listening
struct timeval tv;
tv.tv_sec = 120;
setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv, sizeof(tv));
// accepting a client
int client_socket = accept(socketfd, (struct sockaddr *) &address_, (socklen_t *) &address_);
if (client_socket == -1) {
cout << "Error accepting a client" << endl;
stop();
continue;
}
cout << "waiting for message" << endl;
//open a new thread for each client, clones the handler to avoid collisions, and
//if we have got 10 clients, close the server
client[i] = thread(&ClientHandler::handleClient, handler->clone(), client_socket);
i++;
if (i == 10) {
stop();
}
}
}
close(socketfd);
return;
}