Files
zigp2p/examples/complete_app.zig
2026-02-06 21:03:59 -03:00

261 lines
9.7 KiB
Zig

//! Complete P2P Application Example
//!
//! This example demonstrates a full-featured P2P application that combines:
//! - Network management with peer discovery
//! - File sharing between peers
//! - Message exchange and protocol handling
//! - Event system and statistics
//! - Connection management
//!
//! This serves as a comprehensive reference for using the P2P library.
const std = @import("std");
const p2p_lib = @import("p2p");
const core = @import("core");
const network = @import("network");
const protocol = @import("protocol");
const files = @import("files");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const Address = core.address.Address;
/// Application state tracking
const AppState = struct {
running: bool = true,
peers_connected: usize = 0,
files_shared: usize = 0,
messages_exchanged: usize = 0,
bytes_transferred: usize = 0,
};
pub fn main() !void {
const allocator = std.heap.page_allocator;
std.debug.print("=== Complete P2P Application ===\n\n", .{});
std.debug.print("Demonstrating all major features of the P2P library.\n\n", .{});
var app_state = AppState{};
// ==========================================
// SECTION 1: Configuration
// ==========================================
std.debug.print("--- Section 1: Configuration ---\n", .{});
// Default configuration
var config = P2PConfig.default();
std.debug.print("1.1 Default config created\n", .{});
// Customize for our application
config.network.listen_port = 34000;
config.network.max_connections = 50;
config.network.connection_timeout = 30000;
config.file_sharing.max_concurrent_uploads = 5;
config.file_sharing.max_concurrent_downloads = 5;
config.protocol.max_message_size = 1024 * 1024; // 1MB
std.debug.print("1.2 Configuration customized:\n", .{});
std.debug.print(" Listen port: {d}\n", .{config.network.listen_port});
std.debug.print(" Max connections: {d}\n", .{config.network.max_connections});
std.debug.print(" Max message size: {d} KB\n", .{config.protocol.max_message_size / 1024});
// ==========================================
// SECTION 2: Initialization
// ==========================================
std.debug.print("\n--- Section 2: Initialization ---\n", .{});
var p2p = try P2P.init(allocator, config);
defer p2p.deinit();
std.debug.print("2.1 P2P instance initialized\n", .{});
std.debug.print(" State: {}\n", .{p2p.state});
// ==========================================
// SECTION 3: Starting the Node
// ==========================================
std.debug.print("\n--- Section 3: Starting Node ---\n", .{});
try p2p.start();
std.debug.print("3.1 Node started\n", .{});
std.debug.print(" State: {}\n", .{p2p.state});
std.debug.print(" Running: {}\n", .{p2p.running});
// Start listening
const listen_addr = try Address.parse("127.0.0.1:34001");
try p2p.startListening(listen_addr);
std.debug.print("3.2 Listening on 127.0.0.1:34001\n", .{});
// ==========================================
// SECTION 4: File Sharing Setup
// ==========================================
std.debug.print("\n--- Section 4: File Sharing ---\n", .{});
// Create test files
std.debug.print("4.1 Creating test files...\n", .{});
const test_files = [_]struct { name: []const u8, content: []const u8 }{
.{ .name = "./tests/test_data/app_test1.txt", .content = "Test file 1 for P2P sharing application.\nThis demonstrates file sharing capabilities.\n" },
.{ .name = "./tests/test_data/app_test2.txt", .content = "Test file 2 with different content.\nMultiple files can be shared simultaneously.\n" },
};
for (test_files) |tf| {
const file = try std.fs.cwd().createFile(tf.name, .{});
try file.writeAll(tf.content);
file.close();
std.debug.print(" Created: {s}\n", .{tf.name});
}
// Add files to sharing system
std.debug.print("4.2 Adding files to sharing system...\n", .{});
for (test_files) |tf| {
if (p2p.addFile(tf.name)) |session_id| {
std.debug.print(" {s} -> session {d}\n", .{ tf.name, session_id });
app_state.files_shared += 1;
} else |_| {
std.debug.print(" {s} -> (file manager not initialized)\n", .{tf.name});
}
}
// ==========================================
// SECTION 5: Network Operations
// ==========================================
std.debug.print("\n--- Section 5: Network Operations ---\n", .{});
// Create a second P2P instance to test connectivity
std.debug.print("5.1 Creating second P2P instance for testing...\n", .{});
var config2 = P2PConfig.default();
config2.network.listen_port = 34002;
var p2p2 = try P2P.init(allocator, config2);
defer p2p2.deinit();
try p2p2.start();
std.debug.print(" Second instance started\n", .{});
// Connect p2p2 to p2p1
std.debug.print("5.2 Connecting instances...\n", .{});
const peer_id = try p2p2.connectToPeer(listen_addr);
std.debug.print(" Connected! Peer ID: {x}{x}{x}{x}...\n", .{
peer_id.bytes[0],
peer_id.bytes[1],
peer_id.bytes[2],
peer_id.bytes[3],
});
app_state.peers_connected += 1;
// Accept on p2p1
try p2p.update();
std.debug.print(" Connection accepted by first instance\n", .{});
// ==========================================
// SECTION 6: Message Exchange
// ==========================================
std.debug.print("\n--- Section 6: Message Exchange ---\n", .{});
// Send messages between peers
std.debug.print("6.1 Sending messages...\n", .{});
const messages = [_][]const u8{
"Hello from peer 2!",
"This is a test message.",
"P2P communication working!",
};
for (messages, 0..) |msg, i| {
const msg_id = try p2p2.sendMessage(peer_id, 0x80, msg);
std.debug.print(" [{d}] Sent: \"{s}\" (ID: {d})\n", .{ i + 1, msg, msg_id });
app_state.messages_exchanged += 1;
}
// Process on receiver
try p2p.update();
std.debug.print("6.2 Messages processed by receiver\n", .{});
// ==========================================
// SECTION 7: Event Handling
// ==========================================
std.debug.print("\n--- Section 7: Event Handling ---\n", .{});
std.debug.print("7.1 Checking events on both instances...\n", .{});
// Check events on p2p1
var event_count: usize = 0;
while (p2p.getEventCount() > 0) {
if (p2p.getNextEvent()) |event| {
std.debug.print(" [P2P1] Event: {}\n", .{event.event_type});
event_count += 1;
}
}
// Check events on p2p2
while (p2p2.getEventCount() > 0) {
if (p2p2.getNextEvent()) |event| {
std.debug.print(" [P2P2] Event: {}\n", .{event.event_type});
event_count += 1;
}
}
std.debug.print(" Total events processed: {d}\n", .{event_count});
// ==========================================
// SECTION 8: Statistics
// ==========================================
std.debug.print("\n--- Section 8: Statistics ---\n", .{});
std.debug.print("8.1 P2P Instance 1 Stats:\n", .{});
std.debug.print(" Active connections: {d}\n", .{p2p.stats.active_connections.load(.monotonic)});
std.debug.print(" Total connections: {d}\n", .{p2p.stats.total_connections.load(.monotonic)});
std.debug.print(" Messages sent: {d}\n", .{p2p.stats.messages_sent.load(.monotonic)});
std.debug.print(" Messages received: {d}\n", .{p2p.stats.messages_received.load(.monotonic)});
std.debug.print("8.2 P2P Instance 2 Stats:\n", .{});
std.debug.print(" Active connections: {d}\n", .{p2p2.stats.active_connections.load(.monotonic)});
std.debug.print(" Messages sent: {d}\n", .{p2p2.stats.messages_sent.load(.monotonic)});
std.debug.print("8.3 Application Stats:\n", .{});
std.debug.print(" Peers connected: {d}\n", .{app_state.peers_connected});
std.debug.print(" Files shared: {d}\n", .{app_state.files_shared});
std.debug.print(" Messages exchanged: {d}\n", .{app_state.messages_exchanged});
// ==========================================
// SECTION 9: Graceful Shutdown
// ==========================================
std.debug.print("\n--- Section 9: Graceful Shutdown ---\n", .{});
std.debug.print("9.1 Disconnecting peers...\n", .{});
try p2p2.disconnectPeer(peer_id);
std.debug.print(" Peer disconnected\n", .{});
std.debug.print("9.2 Stopping instances...\n", .{});
try p2p2.stop();
std.debug.print(" Instance 2 stopped\n", .{});
try p2p.stop();
std.debug.print(" Instance 1 stopped\n", .{});
// ==========================================
// SECTION 10: Cleanup
// ==========================================
std.debug.print("\n--- Section 10: Cleanup ---\n", .{});
// Remove test files
for (test_files) |tf| {
std.fs.cwd().deleteFile(tf.name) catch {};
}
std.debug.print("10.1 Test files removed\n", .{});
app_state.running = false;
std.debug.print("10.2 Application state: running = {}\n", .{app_state.running});
std.debug.print("\n=== Complete P2P Application Finished ===\n", .{});
std.debug.print("\nAll major features demonstrated successfully:\n", .{});
std.debug.print(" - Configuration and initialization\n", .{});
std.debug.print(" - Starting and listening\n", .{});
std.debug.print(" - File sharing setup\n", .{});
std.debug.print(" - Peer connection\n", .{});
std.debug.print(" - Message exchange\n", .{});
std.debug.print(" - Event handling\n", .{});
std.debug.print(" - Statistics tracking\n", .{});
std.debug.print(" - Graceful shutdown\n", .{});
}