Working on server
This commit is contained in:
1 parent
ea26d6fb23
commit
1348efb5fe
13 files changed
+761
-193
No files matched your search
@@ -25,7 +25,10 @@ add_subdirectory("${BOOST_SRC_DIR}/libs/predef" boost-predef-build EXCLUDE_FROM_
|
||||
# EXCLUDE_FROM_ALL гарантирует, что мы собираем только то, что линкуем
|
||||
|
||||
# Исполняемый файл сервера
|
||||
add_executable(Server main.cpp)
|
||||
add_executable(Server
|
||||
server.cpp
|
||||
../src/network/ClientState.h
|
||||
)
|
||||
|
||||
target_include_directories(Server PRIVATE ${BOOST_SRC_DIR})
|
||||
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
#include <boost/beast/core.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace net = boost::asio;
|
||||
using tcp = net::ip::tcp;
|
||||
|
||||
class Session : public std::enable_shared_from_this<Session> {
|
||||
websocket::stream<beast::tcp_stream> ws_;
|
||||
beast::flat_buffer buffer_;
|
||||
int id_;
|
||||
|
||||
public:
|
||||
explicit Session(tcp::socket&& socket, int id)
|
||||
: ws_(std::move(socket)), id_(id) {
|
||||
}
|
||||
|
||||
void run() {
|
||||
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
||||
if (ec) return;
|
||||
std::cout << "Client " << self->id_ << " connected\n";
|
||||
// Ñðàçó îòïðàâëÿåì ID êëèåíòó
|
||||
self->send_message("ID:" + std::to_string(self->id_));
|
||||
self->do_read();
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
void do_read() {
|
||||
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
||||
if (ec) return;
|
||||
std::string msg = beast::buffers_to_string(self->buffer_.data());
|
||||
|
||||
if (msg == "PING") {
|
||||
self->send_message("PONG");
|
||||
}
|
||||
|
||||
self->buffer_.consume(self->buffer_.size());
|
||||
self->do_read();
|
||||
});
|
||||
}
|
||||
|
||||
void send_message(std::string msg) {
|
||||
auto ss = std::make_shared<std::string>(std::move(msg));
|
||||
ws_.async_write(net::buffer(*ss), [ss](beast::error_code, std::size_t) {});
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
try {
|
||||
net::io_context ioc;
|
||||
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8080} };
|
||||
int next_id = 1000;
|
||||
|
||||
std::cout << "Server started on port 8080...\n";
|
||||
|
||||
auto do_accept = [&](auto& self_fn) -> void {
|
||||
acceptor.async_accept([&, self_fn](beast::error_code ec, tcp::socket socket) {
|
||||
if (!ec) {
|
||||
std::make_shared<Session>(std::move(socket), next_id++)->run();
|
||||
}
|
||||
self_fn(self_fn);
|
||||
});
|
||||
};
|
||||
|
||||
do_accept(do_accept);
|
||||
ioc.run();
|
||||
}
|
||||
catch (std::exception const& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
#include <boost/beast/core.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <Eigen/Dense>
|
||||
#define _USE_MATH_DEFINES
|
||||
#include <math.h>
|
||||
#include "../src/network/ClientState.h"
|
||||
|
||||
// Âñïîìîãàòåëüíûé split
|
||||
std::vector<std::string> split(const std::string& s, char delimiter) {
|
||||
std::vector<std::string> tokens;
|
||||
std::string token;
|
||||
std::istringstream tokenStream(s);
|
||||
while (std::getline(tokenStream, token, delimiter)) {
|
||||
tokens.push_back(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace net = boost::asio;
|
||||
using tcp = net::ip::tcp;
|
||||
|
||||
class Session;
|
||||
|
||||
std::vector<std::shared_ptr<Session>> g_sessions;
|
||||
std::mutex g_sessions_mutex;
|
||||
|
||||
class Session : public std::enable_shared_from_this<Session> {
|
||||
websocket::stream<beast::tcp_stream> ws_;
|
||||
beast::flat_buffer buffer_;
|
||||
int id_;
|
||||
ClientState state_;
|
||||
|
||||
void process_message(const std::string& msg) {
|
||||
auto now_server = std::chrono::steady_clock::now();
|
||||
|
||||
// Ïðåäïîëîæèì ôîðìàò ñîîáùåíèé:
|
||||
// ROT:ANGLE:MAG:TIMESTAMP
|
||||
// VEL:SELECTED_VEL:TIMESTAMP
|
||||
auto parts = split(msg, ':');
|
||||
if (parts.empty()) return;
|
||||
|
||||
std::cout << msg << std::endl;
|
||||
|
||||
auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now_server.time_since_epoch()
|
||||
).count();
|
||||
|
||||
uint64_t clientTimestamp = std::stoull(parts[1]);
|
||||
|
||||
// Ñíà÷àëà ïðîãîíÿåì ñòàíäàðòíóþ ñèìóëÿöèþ "äî òåêóùåãî ìîìåíòà ñåðâåðà"
|
||||
float dt_server = 0.0f;
|
||||
if (state_.lastUpdateServerTime.time_since_epoch().count() > 0) {
|
||||
dt_server = (clientTimestamp - now_ms) * 1000.f;
|
||||
}
|
||||
|
||||
|
||||
if (dt_server > 0) state_.simulate_physics(dt_server);
|
||||
using time_point = std::chrono::steady_clock::time_point;
|
||||
std::chrono::steady_clock::time_point uptime_timepoint{ std::chrono::duration_cast<std::chrono::steady_clock::time_point::duration>(std::chrono::milliseconds(clientTimestamp)) };
|
||||
state_.lastUpdateServerTime = uptime_timepoint;
|
||||
|
||||
|
||||
// Òåïåðü îáðàáàòûâàåì ñïåöèôèêó ñîîáùåíèÿ è ëàã
|
||||
if (parts[0] == "ROT") {
|
||||
state_.discreteAngle = std::stoi(parts[2]);
|
||||
state_.discreteMag = std::stof(parts[3]);
|
||||
state_.apply_lag_compensation(now_server);
|
||||
}
|
||||
else if (parts[0] == "VEL") {
|
||||
state_.selectedVelocity = std::stoi(parts[2]);
|
||||
state_.apply_lag_compensation(now_server);
|
||||
}
|
||||
else if (parts[0] == "PING") {
|
||||
state_.handle_full_sync(parts);
|
||||
state_.apply_lag_compensation(now_server);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public:
|
||||
explicit Session(tcp::socket&& socket, int id)
|
||||
: ws_(std::move(socket)), id_(id) {
|
||||
}
|
||||
|
||||
void init()
|
||||
{
|
||||
state_.lastUpdateServerTime = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
std::string get_state_string() {
|
||||
return state_.get_state_string(id_);
|
||||
}
|
||||
|
||||
void run() {
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||
g_sessions.push_back(shared_from_this());
|
||||
}
|
||||
|
||||
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
||||
if (ec) return;
|
||||
std::cout << "Client " << self->id_ << " connected\n";
|
||||
self->init();
|
||||
self->send_message("ID:" + std::to_string(self->id_));
|
||||
self->do_read();
|
||||
});
|
||||
}
|
||||
|
||||
void tick_physics_global(std::chrono::steady_clock::time_point now) {
|
||||
float dt = 0.0f;
|
||||
|
||||
// Åñëè ýòî ñàìûé ïåðâûé òèê, ïðîñòî çàïîìèíàåì âðåìÿ
|
||||
if (state_.lastUpdateServerTime.time_since_epoch().count() > 0) {
|
||||
dt = std::chrono::duration<float>(now - state_.lastUpdateServerTime).count();
|
||||
}
|
||||
|
||||
if (dt > 0.0001f) {
|
||||
state_.simulate_physics(dt);
|
||||
state_.lastUpdateServerTime = now; // Îáíîâëÿåì âðåìÿ ïîñëå ñèìóëÿöèè
|
||||
}
|
||||
}
|
||||
|
||||
void tick_physics(float dt_s) {
|
||||
state_.simulate_physics(dt_s);
|
||||
}
|
||||
|
||||
void send_message(std::string msg) {
|
||||
auto ss = std::make_shared<std::string>(std::move(msg));
|
||||
ws_.async_write(net::buffer(*ss), [ss](beast::error_code, std::size_t) {});
|
||||
}
|
||||
|
||||
private:
|
||||
void do_read() {
|
||||
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
||||
if (ec)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||
g_sessions.erase(std::remove_if(g_sessions.begin(), g_sessions.end(),
|
||||
[self](const std::shared_ptr<Session>& session) {
|
||||
return session.get() == self.get();
|
||||
}), g_sessions.end());
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = beast::buffers_to_string(self->buffer_.data());
|
||||
self->process_message(msg);
|
||||
|
||||
self->buffer_.consume(self->buffer_.size());
|
||||
self->do_read();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||
|
||||
// 1. Ñèìóëÿöèÿ ôèçèêè äëÿ âñåõ
|
||||
for (auto& session : g_sessions) {
|
||||
session->tick_physics_global(now);
|
||||
}
|
||||
|
||||
static auto last_broadcast = now;
|
||||
if (std::chrono::duration<float>(now - last_broadcast).count() >= 1.0f) {
|
||||
last_broadcast = now;
|
||||
|
||||
auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()
|
||||
).count();
|
||||
|
||||
// Ñîáèðàåì äàííûå âñåõ èãðîêîâ â îäèí ïàêåò
|
||||
std::string snapshot = "WORLD_UPDATE|";
|
||||
snapshot += std::to_string(now_ms) + "|";
|
||||
snapshot += std::to_string(g_sessions.size()) + "|";
|
||||
for (size_t i = 0; i < g_sessions.size(); ++i) {
|
||||
snapshot += g_sessions[i]->get_state_string();
|
||||
if (i < g_sessions.size() - 1) snapshot += ";"; // Ðàçäåëèòåëü ìåæäó èãðîêàìè
|
||||
}
|
||||
|
||||
// Ðàññûëàåì âñåì
|
||||
for (auto& session : g_sessions) {
|
||||
session->send_message(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ÂÀÆÍÎ: Òèêàåì ÷àñòî (50ìñ), à øëåì äàííûå ðåäêî (1000ìñ âûøå)
|
||||
timer.expires_after(std::chrono::milliseconds(50));
|
||||
timer.async_wait([&](const boost::system::error_code& ec) {
|
||||
if (!ec) update_world(timer, ioc);
|
||||
});
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
net::io_context ioc;
|
||||
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8080} };
|
||||
int next_id = 1000;
|
||||
|
||||
std::cout << "Server started on port 8080...\n";
|
||||
|
||||
auto do_accept = [&](auto& self_fn) -> void {
|
||||
acceptor.async_accept([&, self_fn](beast::error_code ec, tcp::socket socket) {
|
||||
if (!ec) {
|
||||
std::make_shared<Session>(std::move(socket), next_id++)->run();
|
||||
}
|
||||
self_fn(self_fn);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
net::steady_timer timer(ioc);
|
||||
update_world(timer, ioc);
|
||||
|
||||
do_accept(do_accept);
|
||||
ioc.run();
|
||||
}
|
||||
catch (std::exception const& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user