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

263 lines
8.6 KiB
Zig

//! Simple P2P Library Usage Example
//!
//! This example demonstrates the basic usage of the P2P library for
//! file sharing and network communication.
const std = @import("std");
const P2P = @import("p2p");
/// Example event callback function
fn myEventCallback(event: P2P.P2PEvent) void {
std.debug.print("Event: {s}", .{@tagName(event.event_type)});
switch (event.data) {
.library_initialized => {
std.debug.print(" - P2P library initialized\n", .{});
},
.library_started => {
std.debug.print(" - P2P library started successfully\n", .{});
},
.library_stopped => {
std.debug.print(" - P2P library stopped\n", .{});
},
.file_shared => {
std.debug.print(" - File shared successfully\n", .{});
},
.file_download_started => {
std.debug.print(" - File download started\n", .{});
},
.file_download_completed => {
std.debug.print(" - File download completed!\n", .{});
},
.peer_connected => {
std.debug.print(" - New peer connected to network\n", .{});
},
.connection_established => {
std.debug.print(" - Connection established with peer\n", .{});
},
.message_sent => {
std.debug.print(" - Message sent successfully\n", .{});
},
.library_error => |data| {
std.debug.print(" - Error: {s}\n", .{data.message});
},
else => {
std.debug.print("\n", .{});
},
}
}
/// Print current P2P library statistics
fn printStats(p2p: *P2P.P2P) !void {
const stats = p2p.getStats();
const stats_str = try stats.formatString(std.heap.page_allocator);
defer std.heap.page_allocator.free(stats_str);
std.debug.print("\n=== P2P Library Statistics ===\n{s}\n", .{stats_str});
}
/// Example of a simple file sharing application
pub fn main() !void {
const allocator = std.heap.page_allocator;
std.debug.print("Starting P2P Library Example...\n", .{});
// Create P2P instance with default configuration
var p2p = try P2P.createDefault(allocator);
defer p2p.deinit();
// Register our event callback
try p2p.registerCallback(myEventCallback, null);
// Start the P2P library
std.debug.print("Initializing P2P library...\n", .{});
try p2p.start();
// Print initial statistics
try printStats(&p2p);
// Simulate some file sharing operations
std.debug.print("\n=== File Sharing Operations ===\n", .{});
// Note: In a real implementation, you would use actual file paths
// For this example, we'll simulate the operations
// Add a file for sharing (would need actual file in real usage)
// const session_id = try p2p.addFile("/path/to/example.txt");
std.debug.print("Would add file for sharing...\n", .{});
// Send a test message
std.debug.print("Sending test message...\n", .{});
const test_message = "Hello, P2P Network!";
const message_id = p2p.sendMessage(null, 0x80, test_message) catch |err| {
std.debug.print("Message send failed: {s}\n", .{@errorName(err)});
return;
};
std.debug.print("Message sent with ID: {d}\n", .{message_id});
// Connect to a peer (would need actual address in real usage)
std.debug.print("Connecting to peer...\n", .{});
var test_address = P2P.Address.init();
test_address.port = 8080;
const peer_id = p2p.connectToPeer(test_address) catch |err| {
std.debug.print("Connection failed: {s}\n", .{@errorName(err)});
return;
};
std.debug.print("Connected to peer: {s}\n", .{&peer_id.bytes});
// Main event processing loop
std.debug.print("\n=== Event Processing Loop ===\n", .{});
var running = true;
var iteration: u32 = 0;
while (running) {
iteration += 1;
// Process all pending events
const events_processed = p2p.processAllEvents();
if (events_processed > 0) {
std.debug.print("Processed {d} events in iteration {d}\n", .{events_processed, iteration});
}
// Print statistics every 10 iterations
if (iteration % 10 == 0) {
try printStats(&p2p);
}
// Simulate some periodic operations
if (iteration % 5 == 0) {
// Send periodic heartbeat message
const heartbeat = "Heartbeat message";
_ = p2p.sendMessage(null, 0x81, heartbeat) catch {};
}
// Check if we should stop (after 50 iterations for demo)
if (iteration >= 50) {
std.debug.print("Demo iteration limit reached, stopping...\n", .{});
running = false;
}
// Sleep briefly to prevent busy-waiting
std.Thread.sleep(100 * std.time.ns_per_ms); // 100ms
}
// Final statistics
try printStats(&p2p);
// Stop the P2P library
std.debug.print("\nStopping P2P library...\n", .{});
try p2p.stop();
std.debug.print("P2P Library Example completed successfully!\n", .{});
}
/// Example of configuring P2P for different use cases
pub fn configureExamples() !void {
const allocator = std.heap.page_allocator;
std.debug.print("\n=== P2P Configuration Examples ===\n", .{});
// High performance configuration
{
std.debug.print("Creating high-performance P2P instance...\n", .{});
var p2p_hp = try P2P.createHighPerformance(allocator);
defer p2p_hp.deinit();
const config = p2p_hp.config;
std.debug.print("High-performance config: {d} max connections, {d} max threads\n",
.{ config.network.max_connections, config.library.max_threads });
}
// Low resource configuration
{
std.debug.print("Creating low-resource P2P instance...\n", .{});
var p2p_lr = try P2P.createLowResource(allocator);
defer p2p_lr.deinit();
const config = p2p_lr.config;
std.debug.print("Low-resource config: {d} max connections, {d} max threads\n",
.{ config.network.max_connections, config.library.max_threads });
}
// Custom configuration
{
std.debug.print("Creating custom P2P instance...\n", .{});
var custom_config = P2P.P2PConfig.default();
custom_config.network.listen_port = 9999;
custom_config.network.max_connections = 100;
custom_config.file_sharing.max_concurrent_downloads = 5;
custom_config.events.enable_logging = true;
var p2p_custom = try P2P.init(allocator, custom_config);
defer p2p_custom.deinit();
std.debug.print("Custom config: port {d}, {d} max connections\n",
.{ p2p_custom.config.network.listen_port, p2p_custom.config.network.max_connections });
}
}
/// Example of advanced event handling
pub fn advancedEventExample() !void {
const allocator = std.heap.page_allocator;
var p2p = try P2P.createDefault(allocator);
defer p2p.deinit();
// Create custom event context
const EventContext = struct {
messages_received: u32,
files_shared: u32,
peers_connected: u32,
fn new() @This() {
return .{
.messages_received = 0,
.files_shared = 0,
.peers_connected = 0,
};
}
};
var context = EventContext.new();
// Advanced callback with context tracking
const advanced_callback: P2P.EventCallback = struct {
fn callback(event: P2P.P2PEvent) void {
_ = event;
// This would be a more sophisticated callback in practice
}
}.callback;
try p2p.registerCallback(advanced_callback, &context);
std.debug.print("Advanced event handling example configured\n", .{});
// The rest would demonstrate sophisticated event processing...
}
/// Command-line argument parsing for the example
pub fn parseArgs() !P2P.P2PConfig {
const allocator = std.heap.page_allocator;
// In a real implementation, this would parse command line arguments
// For now, return a default configuration
_ = allocator;
return P2P.P2PConfig.default();
}
/// Usage information
pub fn printUsage() void {
std.debug.print(
\\P2P Library Example
\\
\\Usage: p2p_example [options]
\\
\\Options:
\\ --high-performance Use high-performance configuration
\\ --low-resource Use low-resource configuration
\\ --custom-port <port> Use custom listen port
\\ --help Show this help message
\\
);
}