53 std::cout <<
"=== TCP Echo Server Example ===" << std::endl;
61 constexpr uint16_t port = 9000;
63 auto server = tcp.create_server({
65 .server_id =
"EchoServer",
69 std::mutex sessions_mutex;
70 std::map<std::string, std::shared_ptr<interfaces::i_session>> sessions;
73 server->set_connection_callback(
74 [&sessions, &sessions_mutex](std::shared_ptr<interfaces::i_session> session) {
75 std::lock_guard<std::mutex> lock(sessions_mutex);
76 std::string id(session->id());
77 sessions[id] = session;
78 std::cout <<
"[Server] Client connected: " <<
id << std::endl;
82 server->set_disconnection_callback(
83 [&sessions, &sessions_mutex](std::string_view session_id) {
84 std::lock_guard<std::mutex> lock(sessions_mutex);
85 sessions.erase(std::string(session_id));
86 std::cout <<
"[Server] Client disconnected: " << session_id << std::endl;
90 server->set_receive_callback(
91 [&sessions, &sessions_mutex](std::string_view session_id,
92 const std::vector<uint8_t>& data) {
93 std::string
message(data.begin(), data.end());
94 std::cout <<
"[Server] Received from " << session_id <<
": " <<
message
98 std::shared_ptr<interfaces::i_session> session;
100 std::lock_guard<std::mutex> lock(sessions_mutex);
101 auto it = sessions.find(std::string(session_id));
102 if (it != sessions.end()) {
103 session = it->second;
108 auto result = session->send(std::vector<uint8_t>(data));
109 if (result.is_err()) {
110 std::cerr <<
"[Server] Echo failed: " << result.error().message
117 server->set_error_callback(
118 [](std::string_view session_id, std::error_code ec) {
119 std::cerr <<
"[Server] Error on " << session_id <<
": " << ec.message()
124 auto result = server->start(port);
125 if (result.is_err()) {
126 std::cerr <<
"Failed to start server: " << result.error().message << std::endl;
130 std::cout <<
"[Server] Listening on port " << port << std::endl;
131 std::cout <<
"[Server] Press Ctrl+C to stop." << std::endl;
135 std::this_thread::sleep_for(std::chrono::milliseconds(100));
139 std::cout <<
"\n[Server] Shutting down..." << std::endl;
140 auto stop_result = server->stop();
141 if (stop_result.is_err()) {
142 std::cerr <<
"[Server] Stop error: " << stop_result.error().message << std::endl;
145 std::cout <<
"[Server] Stopped." << std::endl;