Network System 0.1.1
High-performance modular networking library for scalable client-server applications
Loading...
Searching...
No Matches
modern_usage.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, šŸ€ā˜€šŸŒ•šŸŒ„ 🌊
3// See the LICENSE file in the project root for full license information.
4
24#include <iostream>
25#include <memory>
26#include <thread>
27#include <chrono>
28#include <vector>
29#include <future>
30
31// Include modern network_system API
33
34using namespace kcenon::network;
35using namespace std::chrono_literals;
36
41public:
42 ModernServer(const std::string& id) : server_id_(id) {
43 server_ = std::make_shared<core::messaging_server>(server_id_);
44 bridge_ = std::make_shared<integration::messaging_bridge>();
45
46 // Set up thread pool interface
47 bridge_->set_thread_pool_interface(
49 );
50
51 std::cout << "[Modern Server] Created with ID: " << server_id_ << std::endl;
52 }
53
54 bool start(uint16_t port) {
55 auto result = server_->start_server(port);
56 if (result.is_err()) {
57 std::cerr << "[Modern Server] Failed to start: " << result.error().message
58 << " (code: " << result.error().code << ")" << std::endl;
59 return false;
60 }
61
62 port_ = port;
63 std::cout << "[Modern Server] Started on port " << port << std::endl;
64 return true;
65 }
66
67 bool stop() {
68 auto result = server_->stop_server();
69 if (result.is_err()) {
70 std::cerr << "[Modern Server] Failed to stop: " << result.error().message
71 << " (code: " << result.error().code << ")" << std::endl;
72 return false;
73 }
74
75 std::cout << "[Modern Server] Stopped" << std::endl;
76 return true;
77 }
78
80 async_enabled_ = true;
81 std::cout << "[Modern Server] Async processing enabled" << std::endl;
82 }
83
85 auto metrics = bridge_->get_metrics();
87
88 std::cout << "\n=== Server Statistics ===" << std::endl;
89 std::cout << "Network Metrics:" << std::endl;
90 std::cout << " Messages sent: " << metrics.messages_sent << std::endl;
91 std::cout << " Messages received: " << metrics.messages_received << std::endl;
92 std::cout << " Bytes sent: " << metrics.bytes_sent << std::endl;
93 std::cout << " Bytes received: " << metrics.bytes_received << std::endl;
94 std::cout << " Active connections: " << metrics.connections_active << std::endl;
95
96 std::cout << "\nThread Pool Metrics:" << std::endl;
97 std::cout << " Worker threads: " << thread_metrics.worker_threads << std::endl;
98 std::cout << " Pending tasks: " << thread_metrics.pending_tasks << std::endl;
99 std::cout << " Completed tasks: " << thread_metrics.completed_tasks << std::endl;
100 }
101
102private:
103 void process_message(const std::string& client_id, const std::string& message) {
104 std::cout << "[Modern Server] Processing from " << client_id
105 << ": " << message << std::endl;
106
107 if (async_enabled_) {
108 // Process asynchronously using thread pool
110 auto future = thread_mgr.submit_task([message]() {
111 // Simulate complex processing
112 std::this_thread::sleep_for(50ms);
113 std::cout << "[Async Processor] Completed processing: " << message << std::endl;
114 });
115
116 // Don't wait - let it process in background
117 futures_.push_back(std::move(future));
118 }
119
120 // Use container system for demonstration
121 auto& container_mgr = integration::container_manager::instance();
122 std::string response = "Processed: " + message;
123
124 // Serialize and deserialize to demonstrate container usage
125 auto serialized = container_mgr.serialize(std::any(response));
126 auto deserialized = container_mgr.deserialize(serialized);
127
128 if (deserialized.has_value()) {
129 std::cout << "[Modern Server] Container processed: "
130 << std::any_cast<std::string>(deserialized) << std::endl;
131 }
132 }
133
134 std::string server_id_;
135 uint16_t port_ = 0;
136 bool async_enabled_ = false;
137 std::shared_ptr<core::messaging_server> server_;
138 std::shared_ptr<integration::messaging_bridge> bridge_;
139 std::vector<std::future<void>> futures_;
140};
141
146public:
147 ModernClient(const std::string& id) : client_id_(id) {
148 client_ = std::make_shared<core::messaging_client>(client_id_);
149 std::cout << "[Modern Client] Created with ID: " << client_id_ << std::endl;
150 }
151
152 bool connect(const std::string& host, uint16_t port) {
153 auto result = client_->start_client(host, port);
154 if (result.is_err()) {
155 std::cerr << "[Modern Client] Failed to connect: " << result.error().message
156 << " (code: " << result.error().code << ")" << std::endl;
157 return false;
158 }
159
160 std::cout << "[Modern Client] Connecting to " << host << ":" << port << std::endl;
161 std::this_thread::sleep_for(200ms); // Give time to connect
162 return true;
163 }
164
165 size_t send_batch(const std::vector<std::string>& messages) {
166 std::cout << "[Modern Client] Sending batch of " << messages.size()
167 << " messages" << std::endl;
168
169 size_t successful = 0;
170 for (const auto& msg : messages) {
171 std::vector<uint8_t> data(msg.begin(), msg.end());
172 auto result = client_->send_packet(data);
173
174 if (result.is_err()) {
175 std::cerr << "[Modern Client] Failed to send message: " << result.error().message
176 << " (code: " << result.error().code << ")" << std::endl;
177 } else {
178 successful++;
179 }
180
181 std::this_thread::sleep_for(50ms);
182 }
183
184 std::cout << "[Modern Client] Successfully sent " << successful << "/" << messages.size()
185 << " messages" << std::endl;
186 return successful;
187 }
188
189 void send_async(const std::string& message) {
191 thread_mgr.submit_task([this, message]() {
192 std::vector<uint8_t> data(message.begin(), message.end());
193 auto result = client_->send_packet(data);
194
195 if (result.is_err()) {
196 std::cerr << "[Modern Client] Async send failed: " << result.error().message
197 << " (code: " << result.error().code << ")" << std::endl;
198 } else {
199 std::cout << "[Modern Client] Async sent: " << message << std::endl;
200 }
201 });
202 }
203
204 bool disconnect() {
205 auto result = client_->stop_client();
206 if (result.is_err()) {
207 std::cerr << "[Modern Client] Failed to disconnect: " << result.error().message
208 << " (code: " << result.error().code << ")" << std::endl;
209 return false;
210 }
211
212 std::cout << "[Modern Client] Disconnected" << std::endl;
213 return true;
214 }
215
216private:
217 std::string client_id_;
218 std::shared_ptr<core::messaging_client> client_;
219};
220
225 std::cout << "\n=== Advanced Features Demo ===" << std::endl;
226
227 // Custom container with serialization
228 auto custom_container = std::make_shared<integration::basic_container>();
229
230 // Set custom serializer for complex types
231 custom_container->set_serializer([](const std::any& data) {
232 std::vector<uint8_t> result;
233 if (data.type() == typeid(std::vector<int>)) {
234 auto vec = std::any_cast<std::vector<int>>(data);
235 result.reserve(vec.size() * sizeof(int));
236 for (int val : vec) {
237 auto bytes = reinterpret_cast<const uint8_t*>(&val);
238 result.insert(result.end(), bytes, bytes + sizeof(int));
239 }
240 }
241 return result;
242 });
243
244 // Register custom container
246 "custom_vector_serializer", custom_container
247 );
248
249 // Test custom serialization
250 std::vector<int> test_data = {1, 2, 3, 4, 5};
251 auto serialized = custom_container->serialize(std::any(test_data));
252 std::cout << "Custom serialized " << test_data.size()
253 << " integers to " << serialized.size() << " bytes" << std::endl;
254
255 // Thread pool advanced usage
257 std::vector<std::future<void>> tasks;
258
259 // Submit multiple delayed tasks
260 for (int i = 1; i <= 3; ++i) {
261 auto future = thread_mgr.submit_delayed_task(
262 [i]() {
263 std::cout << "[Delayed Task " << i << "] Executed after delay" << std::endl;
264 },
265 std::chrono::milliseconds(i * 100)
266 );
267 tasks.push_back(std::move(future));
268 }
269
270 // Wait for all tasks
271 for (auto& future : tasks) {
272 future.wait();
273 }
274
275 std::cout << "All advanced features demonstrated successfully" << std::endl;
276}
277
281int main(int argc, char* argv[]) {
282 std::cout << "=== Modern Network System Usage Demo ===" << std::endl;
283 std::cout << "Demonstrating the new API with all integration features" << std::endl;
284
285 // Initialize using modern API
286 kcenon::network::compat::initialize();
287 std::cout << "\nāœ“ Network system initialized" << std::endl;
288
289 try {
290 // Create modern server
291 ModernServer server("modern_server_001");
292 server.enable_async_processing();
293
294 if (!server.start(9090)) {
295 std::cerr << "Failed to start server, aborting demo" << std::endl;
296 return 1;
297 }
298
299 // Allow server to start
300 std::this_thread::sleep_for(500ms);
301
302 // Create modern client
303 ModernClient client("modern_client_001");
304
305 if (!client.connect("127.0.0.1", 9090)) {
306 std::cerr << "Failed to connect client, stopping server" << std::endl;
307 server.stop();
308 return 1;
309 }
310
311 // Send batch messages
312 std::vector<std::string> batch = {
313 "Modern message 1",
314 "Modern message 2",
315 "Modern message 3"
316 };
317 size_t sent = client.send_batch(batch);
318
319 if (sent < batch.size()) {
320 std::cout << "[Warning] Not all messages were sent successfully" << std::endl;
321 }
322
323 // Send async messages
324 for (int i = 1; i <= 3; ++i) {
325 client.send_async("Async message " + std::to_string(i));
326 }
327
328 // Wait for async operations
329 std::this_thread::sleep_for(500ms);
330
331 // Show server statistics
332 server.show_statistics();
333
334 // Disconnect
335 if (!client.disconnect()) {
336 std::cout << "[Warning] Client disconnection had issues" << std::endl;
337 }
338
339 // Demonstrate advanced features
341
342 // Stop server
343 if (!server.stop()) {
344 std::cout << "[Warning] Server shutdown had issues" << std::endl;
345 }
346
347 } catch (const std::exception& e) {
348 std::cerr << "Error: " << e.what() << std::endl;
349 return 1;
350 }
351
352 // Shutdown
353 kcenon::network::compat::shutdown();
354 std::cout << "\nāœ“ Network system shutdown complete" << std::endl;
355
356 std::cout << "\n=== Modern Usage Demo Complete ===" << std::endl;
357 std::cout << "All modern features working perfectly!" << std::endl;
358
359 return 0;
360}
int main()
Modern client using new API.
size_t send_batch(const std::vector< std::string > &messages)
std::string client_id_
bool connect(const std::string &host, uint16_t port)
std::shared_ptr< core::messaging_client > client_
ModernClient(const std::string &id)
void send_async(const std::string &message)
Modern server using new API.
void process_message(const std::string &client_id, const std::string &message)
std::shared_ptr< core::messaging_server > server_
void show_statistics()
void enable_async_processing()
ModernServer(const std::string &id)
std::string server_id_
std::shared_ptr< integration::messaging_bridge > bridge_
bool start(uint16_t port)
std::vector< std::future< void > > futures_
auto start_client(std::string_view host, unsigned short port) -> VoidResult
Starts the client and connects to the specified host and port.
auto stop_client() -> VoidResult
Stops the client and disconnects from the server.
auto send_packet(std::vector< uint8_t > &&data) -> VoidResult
Sends data to the connected server.
auto start_server(unsigned short port) -> VoidResult
Starts the server on the specified port.
auto stop_server() -> VoidResult
Stops the server and closes all connections.
void register_container(const std::string &name, std::shared_ptr< container_interface > container)
Register a container implementation.
static container_manager & instance()
Get the singleton instance.
static thread_integration_manager & instance()
Get the singleton instance.
void demonstrate_advanced_features()
Demonstrate advanced features.
Main namespace for all Network System components.
Main header for the Network System.