#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
std::cout << "=== TCP Client Example ===" << std::endl;
constexpr uint16_t port = 9000;
const std::string host = "127.0.0.1";
auto client = tcp.create_client({
.host = host,
.port = port,
.client_id = "ExampleClient",
});
client->set_receive_callback([](const std::vector<uint8_t>& data) {
std::string message(data.begin(), data.end());
std::cout << "[Client] Received: " << message << std::endl;
});
client->set_connected_callback([]() {
std::cout << "[Client] Connected to server." << std::endl;
});
client->set_disconnected_callback([]() {
std::cout << "[Client] Disconnected from server." << std::endl;
});
client->set_error_callback([](std::error_code ec) {
std::cerr << "[Client] Error: " << ec.message() << std::endl;
});
std::cout << "[Client] Connecting to " << host << ":" << port << "..." << std::endl;
auto connect_result = client->start(host, port);
if (connect_result.is_err()) {
std::cerr << "[Client] Connection failed: " << connect_result.error().message
<< std::endl;
return 1;
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
if (!client->is_connected()) {
std::cerr << "[Client] Not connected." << std::endl;
client->stop();
return 1;
}
std::vector<std::string> messages = {
"Hello, server!",
"This is a TCP client example.",
"Goodbye!",
};
for (const auto& msg : messages) {
std::vector<uint8_t> data(msg.begin(), msg.end());
std::cout << "[Client] Sending: " << msg << std::endl;
auto send_result = client->send(std::move(data));
if (send_result.is_err()) {
std::cerr << "[Client] Send failed: " << send_result.error().message
<< std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "[Client] Sending binary data..." << std::endl;
std::vector<uint8_t> binary_data = {0x01, 0x02, 0x03, 0x04, 0xFF};
auto binary_result = client->send(std::move(binary_data));
if (binary_result.is_err()) {
std::cerr << "[Client] Binary send failed: " << binary_result.error().message
<< std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "[Client] Disconnecting..." << std::endl;
auto stop_result = client->stop();
if (stop_result.is_err()) {
std::cerr << "[Client] Stop error: " << stop_result.error().message << std::endl;
}
std::cout << "[Client] Done." << std::endl;
return 0;
}
Simplified facade for creating TCP clients and servers.
Main namespace for all Network System components.
Simplified facade for creating TCP clients and servers.