49 constexpr uint16_t port = 9003;
51 auto server = udp.create_server({
53 .server_id =
"UdpEchoServer",
56 std::mutex sessions_mutex;
57 std::unordered_map<std::string, std::shared_ptr<interfaces::i_session>> sessions;
59 server->set_connection_callback(
60 [&sessions, &sessions_mutex](std::shared_ptr<interfaces::i_session> session) {
61 std::lock_guard<std::mutex> lock(sessions_mutex);
62 sessions[std::string(session->id())] = session;
63 std::cout <<
"[Server] New peer: " << session->id() << std::endl;
66 server->set_disconnection_callback(
67 [&sessions, &sessions_mutex](std::string_view session_id) {
68 std::lock_guard<std::mutex> lock(sessions_mutex);
69 sessions.erase(std::string(session_id));
72 server->set_receive_callback(
73 [&sessions, &sessions_mutex](std::string_view session_id,
74 const std::vector<uint8_t>& data) {
75 std::string msg(data.begin(), data.end());
76 std::cout <<
"[Server] From " << session_id <<
": " << msg << std::endl;
79 std::shared_ptr<interfaces::i_session> session;
81 std::lock_guard<std::mutex> lock(sessions_mutex);
82 auto it = sessions.find(std::string(session_id));
83 if (it != sessions.end()) {
88 std::string echo =
"Echo: " + msg;
89 std::vector<uint8_t> echo_data(echo.begin(), echo.end());
90 session->send(std::move(echo_data));
94 server->set_error_callback(
95 [](std::string_view session_id, std::error_code ec) {
96 std::cerr <<
"[Server] Error on " << session_id <<
": " << ec.message()
100 std::cout <<
"[Server] UDP echo server on port " << port << std::endl;
103 std::this_thread::sleep_for(std::chrono::milliseconds(100));
106 std::cout <<
"[Server] Stopped." << std::endl;
111 std::this_thread::sleep_for(std::chrono::milliseconds(300));
114 auto client = udp.create_client({
117 .client_id =
"UdpClient",
120 client->set_receive_callback([](
const std::vector<uint8_t>& data) {
121 std::string msg(data.begin(), data.end());
122 std::cout <<
"[Client] Received: " << msg << std::endl;
125 client->set_error_callback([](std::error_code ec) {
126 std::cerr <<
"[Client] Error: " << ec.message() << std::endl;
130 std::vector<std::string> messages = {
132 "Datagrams preserve boundaries",
133 "Fast and lightweight",
136 for (
const auto& msg : messages) {
137 std::vector<uint8_t> data(msg.begin(), msg.end());
138 std::cout <<
"[Client] Sending: " << msg << std::endl;
140 auto result = client->send(std::move(data));
141 if (result.is_err()) {
142 std::cerr <<
"[Client] Send failed: " << result.error().message << std::endl;
145 std::this_thread::sleep_for(std::chrono::milliseconds(500));
149 std::this_thread::sleep_for(std::chrono::milliseconds(500));