-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
119 lines (83 loc) · 2.47 KB
/
Server.cpp
File metadata and controls
119 lines (83 loc) · 2.47 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
#include "Server.h"
char* wrkdir;
Server::Server(const char* serverIP, int port)
{
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if(socketfd == -1){
std::cout << "Err Sock" << std::cout;
throw(1);
}
struct sockaddr_in adr = {0};
adr.sin_family = AF_INET;
adr.sin_addr.s_addr = inet_addr(serverIP);
adr.sin_port = htons(port);
if(bind(socketfd, (struct sockaddr*) &adr, sizeof(adr)) == -1){
std::cout << "Err bind" << std::endl;
throw(2);
}
std::cout << "Bound" << std::endl;
if(listen(socketfd, 5) == -1){
std::cout << "Error listen" << std::endl;
throw(3);
}
std::cout << "listening" << std::endl;
}
Server::~Server()
{
shutdown(socketfd, 2);
for(auto& th : threads){
th.join();
}
}
void Server::accept_new()
{
struct sockaddr_storage clientaddr;
int clientsock;
socklen_t clientsize = sizeof(clientaddr);
clientsock = accept(socketfd, (struct sockaddr*)&clientaddr, &clientsize);
struct timeval timeout;
timeout.tv_sec = 20;
timeout.tv_usec = 0;
if(setsockopt(clientsock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0){
std::cout << "Cannot set properties" << std::endl;
std::cout << errno << std::endl;
throw(4);
}
//std::cout << clientsock << std::endl;
//std::thread thread(handle_request, clientsock);
threads.emplace_back(handle_request, clientsock);
}
void Server::clean_threads()
{
for(int i = threads.size() - 1; i >= 0; i--){
if(threads[i].joinable()){
threads[i].join();
threads.erase(threads.begin() + i);
}
}
}
void handle_request(int clientsock)
{
char buf[1024] = {0};
int sizeRecv = recv(clientsock, buf, 1024, 0);
std::cout << buf << std::endl;
bool persist = 0;
if(sizeRecv > 0){
do{
HTTPRequest req(buf, wrkdir);
persist = req.keep_alive;
const std::string res = req.get_response();
std::cout << res << std::endl;
int len = res.length();
int oldlen = 0;
while(len > 0){
send(clientsock, &res.c_str()[oldlen], len, 0);
oldlen = len;
len = res.length() - len;
}
sizeRecv = recv(clientsock, buf, 1024, 0);
}while((sizeRecv > 0) && persist);
}
std::cout << "shutting down" << std::endl;
shutdown(clientsock, 2);
}