-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
75 lines (61 loc) · 1.97 KB
/
main.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <fstream>
#include <csignal>
#include <thread>
#include <algorithm>
#include "absl/strings/str_format.h"
#include "absl/log/log.h"
#include "handlers.h"
#include "logger.h"
#include "socket_setup.h"
// для POSIX систем
#ifdef _POSIX_C_SOURCE
#define USE_SIGACTION
#endif
FILE *log_file = nullptr;
bool server_running = true;
void handle_signal(int sig)
{
if (sig == SIGINT)
{
server_running = false;
LOG(INFO) << "Сигнал остановки получен. Сервер останавливается...";
}
}
int main()
{
constexpr absl::string_view kFormatString = "Welcome to %s, Number %d!";
std::string s = absl::StrFormat(kFormatString, "The Village", 6);
absl::PrintF("Trying to request TITLE: %s \n", s);
std::signal(SIGINT, handle_signal);
int sockfd = setup_socket();
setup_server(sockfd);
log_file = log_file_init();
if (log_file == nullptr)
{
perror("Ошибка при инициализации файла лога");
return 1;
}
LOG(INFO) << "Сервер успешно запущен!";
while (server_running)
{
struct sockaddr_in host_addr;
unsigned int host_addr_len = sizeof(host_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&host_addr, &host_addr_len);
if (new_sockfd < 0)
{
perror("Ошибка при подключении");
LOG(INFO) << "Ошибка при подключении";
continue;
}
LOG(INFO) << "Кто-то подключился | Успешно!";
std::shared_ptr<int> new_sockfd_shared;
new_sockfd_shared = std::make_shared<int>(new_sockfd);
std::unique_ptr<std::thread> client_thread(new std::thread(handle_client_thread, new_sockfd_shared.get()));
client_thread->detach();
}
shutdown_server(sockfd);
LOG(INFO) << "Сервер выключен!";
fclose(log_file);
return 0;
}