67 lines
2.2 KiB
C++
67 lines
2.2 KiB
C++
#include "webserver.hpp"
|
||
#include "config.hpp"
|
||
|
||
#include <iostream>
|
||
#include <thread>
|
||
#include <atomic>
|
||
|
||
#include "libs/httplib.h"
|
||
|
||
static std::atomic<bool> g_serverRunning{false};
|
||
static std::thread g_serverThread;
|
||
|
||
static void serverThreadFunc() {
|
||
httplib::Server svr;
|
||
svr.Get("/", [](const httplib::Request&, httplib::Response &res){
|
||
res.set_content("Hello from Cerberus BFSK!", "text/plain");
|
||
});
|
||
|
||
if (!svr.listen("0.0.0.0", 8080)) {
|
||
std::cerr << CLR_RED "[web] Ошибка listen(8080). Возможно, порт занят.\n" CLR_RESET;
|
||
}
|
||
g_serverRunning = false;
|
||
}
|
||
|
||
void webServerStart(AppConfig &config) {
|
||
if (config.webServerRunning) {
|
||
std::cout << CLR_YELLOW "[web] Сервер уже запущен.\n" CLR_RESET;
|
||
return;
|
||
}
|
||
g_serverRunning = true;
|
||
g_serverThread = std::thread(serverThreadFunc);
|
||
|
||
config.webServerRunning = true;
|
||
std::cout << CLR_GREEN "[web] Сервер запущен на порту 8080.\n" CLR_RESET;
|
||
}
|
||
|
||
void webServerConnect(AppConfig &config, const std::string &type, const std::string &ip) {
|
||
if (!config.webServerRunning) {
|
||
std::cout << CLR_YELLOW "[web] Сначала запустите сервер (web start)\n" CLR_RESET;
|
||
return;
|
||
}
|
||
httplib::Client cli(ip.c_str(), 8080);
|
||
if (auto res = cli.Get("/")) {
|
||
if (res->status == 200) {
|
||
std::cout << CLR_CYAN "[web] Ответ от " << ip << ": " << res->body << CLR_RESET "\n";
|
||
} else {
|
||
std::cout << CLR_YELLOW "[web] Подключились, статус: " << res->status << CLR_RESET "\n";
|
||
}
|
||
} else {
|
||
std::cout << CLR_RED "[web] Не удалось подключиться к " << ip << ":8080.\n" CLR_RESET;
|
||
}
|
||
}
|
||
|
||
void webServerStop(AppConfig &config) {
|
||
if (!config.webServerRunning) {
|
||
std::cout << CLR_YELLOW "[web] Сервер не запущен.\n" CLR_RESET;
|
||
return;
|
||
}
|
||
g_serverRunning = false;
|
||
if (g_serverThread.joinable()) {
|
||
g_serverThread.detach();
|
||
}
|
||
|
||
config.webServerRunning = false;
|
||
std::cout << CLR_GREEN "[web] Сервер остановлен (демо).\n" CLR_RESET;
|
||
}
|