Run this server, then connect with the tcp_client example or any TCP client: echo "hello" | nc localhost 9000
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <thread>
}
std::cout << "=== TCP Echo Server Example ===" << std::endl;
constexpr uint16_t port = 9000;
.port = port,
.server_id = "EchoServer",
});
std::mutex sessions_mutex;
std::map<std::string, std::shared_ptr<interfaces::i_session>> sessions;
server->set_connection_callback(
[&sessions, &sessions_mutex](std::shared_ptr<interfaces::i_session> session) {
std::lock_guard<std::mutex> lock(sessions_mutex);
std::string id(session->id());
sessions[id] = session;
std::cout << "[Server] Client connected: " << id << std::endl;
});
server->set_disconnection_callback(
[&sessions, &sessions_mutex](std::string_view session_id) {
std::lock_guard<std::mutex> lock(sessions_mutex);
sessions.erase(std::string(session_id));
std::cout << "[Server] Client disconnected: " << session_id << std::endl;
});
[&sessions, &sessions_mutex](std::string_view session_id,
const std::vector<uint8_t>& data) {
std::cout <<
"[Server] Received from " << session_id <<
": " <<
message
<< std::endl;
std::shared_ptr<interfaces::i_session> session;
{
std::lock_guard<std::mutex> lock(sessions_mutex);
auto it = sessions.find(std::string(session_id));
if (it != sessions.end()) {
session = it->second;
}
}
if (session) {
auto result = session->send(std::vector<uint8_t>(data));
if (result.is_err()) {
std::cerr << "[Server] Echo failed: " << result.error().message
<< std::endl;
}
}
});
[](std::string_view session_id, std::error_code ec) {
std::cerr << "[Server] Error on " << session_id << ": " << ec.message()
<< std::endl;
});
auto result =
server->start(port);
if (result.is_err()) {
std::cerr << "Failed to start server: " << result.error().message << std::endl;
return 1;
}
std::cout << "[Server] Listening on port " << port << std::endl;
std::cout << "[Server] Press Ctrl+C to stop." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "\n[Server] Shutting down..." << std::endl;
auto stop_result =
server->stop();
if (stop_result.is_err()) {
std::cerr << "[Server] Stop error: " << stop_result.error().message << std::endl;
}
std::cout << "[Server] Stopped." << std::endl;
return 0;
}
Simplified facade for creating TCP clients and servers.
Session interface representing an active client-server connection.
@ server
Server-side handling of a request.
Main namespace for all Network System components.
static std::atomic< bool > g_running
Simplified facade for creating TCP clients and servers.