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

211 lines
7.5 KiB
Zig

//! Example server demonstrating P2P core networking usage
//!
//! This example shows how to use the core networking module to create
//! a simple TCP server that accepts connections and echoes messages back.
const std = @import("std");
const net = std.net;
const os = std.os;
const core = @import("core");
const Error = core.Error;
const Address = core.Address;
const Socket = core.Socket;
const Connection = core.Connection;
const ConnectionConfig = core.connection.ConnectionConfig;
const Buffer = core.buffer;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
std.debug.print("=== P2P Core Networking Server Example ===\n", .{});
// Create TCP socket for server
var server_socket = try Socket.init(.tcp, allocator);
defer server_socket.deinit();
// Configure socket
try server_socket.setOption(.reuse_address, 1);
try server_socket.setOption(.keep_alive, 1);
// Bind to address
const bind_address = try Address.parse("127.0.0.1:8080");
std.debug.print("Binding to {s}...\n", .{blk: {
var buf: [128]u8 = undefined;
break :blk bind_address.toStringBuf(&buf);
}});
try server_socket.bind(bind_address);
std.debug.print("Socket bound successfully.\n", .{});
// Start listening
const backlog = 10;
try server_socket.listen(backlog);
std.debug.print("Server listening with backlog {}.\n", .{backlog});
// Accept connections and handle them
var connection_count: u32 = 0;
std.debug.print("\n=== Server is ready - accepting connections ===\n", .{});
// For this example, accept a few connections
while (connection_count < 3) {
std.debug.print("Waiting for connection {}...\n", .{connection_count + 1});
// Accept connection
var client_socket = server_socket.accept() catch |err| {
std.debug.print("Failed to accept connection: {s}\n", .{@errorName(err)});
continue;
};
defer client_socket.deinit();
connection_count += 1;
if (client_socket.getRemoteAddress()) |remote_addr| {
std.debug.print("Accepted connection {} from {s}\n", .{
connection_count,
blk: {
var buf: [128]u8 = undefined;
break :blk remote_addr.toStringBuf(&buf);
},
});
} else {
std.debug.print("Accepted connection {}\n", .{connection_count});
}
// Create connection abstraction
const config = ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 4096,
.timeout_ms = 10000,
.keep_alive = true,
.no_delay = true,
.enable_metrics = true,
};
var connection = try Connection.init(.tcp, config, allocator);
defer connection.deinit();
// Note: In a real implementation, you'd wrap the accepted socket
// For this example, we'll simulate the connection
std.debug.print("Created connection wrapper (ID: {})\n", .{connection.getId()});
// Handle the connection
try handleClient(&connection, allocator, connection_count);
std.debug.print("Completed handling connection {}.\n\n", .{connection_count});
}
std.debug.print("Server shutting down after {} connections.\n", .{connection_count});
}
fn handleClient(connection: *Connection, allocator: std.mem.Allocator, connection_id: u32) !void {
std.debug.print("=== Handling client connection {} ===\n", .{connection_id});
// Show connection info
if (connection.getLocalAddress()) |local_addr| {
std.debug.print("Server local address: {s}\n", .{blk: {
var buf: [128]u8 = undefined;
break :blk local_addr.toStringBuf(&buf);
}});
}
if (connection.getRemoteAddress()) |remote_addr| {
std.debug.print("Client remote address: {s}\n", .{blk: {
var buf: [128]u8 = undefined;
break :blk remote_addr.toStringBuf(&buf);
}});
}
// Create buffers
var send_buffer = try connection.createSendBuffer();
defer send_buffer.release();
var receive_buffer = try connection.createReceiveBuffer();
defer receive_buffer.release();
// Message exchange loop
var message_count: u32 = 0;
while (message_count < 5) {
// Receive data
var data_buffer: [1024]u8 = undefined;
const received = receiveFromSocket(&data_buffer) catch |err| {
if (err == Error.ConnectionTimeout) {
std.debug.print("Client timeout after {} messages\n", .{message_count});
break;
}
return err;
};
if (received == 0) {
std.debug.print("Client disconnected after {} messages\n", .{message_count});
break;
}
message_count += 1;
// Process received message
const received_data = data_buffer[0..received];
std.debug.print("Received message {} ({} bytes): {s}\n", .{
message_count, received, received_data
});
// Create echo response
const response = try std.fmt.allocPrint(allocator,
"Echo {d}: {s}", .{message_count, received_data});
defer allocator.free(response);
std.debug.print("Sending response: {s}\n", .{response});
// Send echo response
try send_buffer.write(response);
try sendBufferToSocket(send_buffer.base.data[0..response.len]);
send_buffer.reset();
// Update connection statistics
connection.getStatsMut().recordReceive(received, 1);
connection.getStatsMut().recordSend(response.len, 1);
}
// Show final statistics for this connection
const stats = connection.getStats();
std.debug.print("Connection {} statistics:\n", .{connection_id});
std.debug.print(" Messages processed: {}\n", .{message_count});
std.debug.print(" Bytes sent: {}\n", .{stats.getBytesSent()});
std.debug.print(" Bytes received: {}\n", .{stats.getBytesReceived()});
std.debug.print(" Connection uptime: {} seconds\n", .{connection.getUptime()});
// Perform health check
const health = connection.checkHealth();
std.debug.print("Final health check: {s}\n", .{@tagName(health.status)});
}
// Simulate receiving data (in a real implementation, this would use the socket)
fn receiveFromSocket(buffer: []u8) Error!usize {
// For this example, we'll simulate receiving some data
// In a real implementation, you would use the actual socket
// Simulate different scenarios
const message_count = @mod(std.time.timestamp(), 5);
switch (message_count) {
0 => return 0, // Simulate client disconnect
else => {
const message = std.fmt.allocPrint(std.heap.page_allocator,
"Client message {}", .{message_count}) catch return Error.OutOfMemory;
defer std.heap.page_allocator.free(message);
const len = @min(message.len, buffer.len);
@memcpy(buffer[0..len], message);
return len;
},
}
}
// Simulate sending data (in a real implementation, this would use the socket)
fn sendBufferToSocket(data: []const u8) Error!void {
// For this example, we just log the data
// In a real implementation, you would use the actual socket
std.debug.print("Simulated send: {s}\n", .{data});
}