tcp-echo.zig (1618B)
1 const std = @import("std"); 2 const pi = @import("pi"); 3 4 const tcp = @import("shared").tcp_protocol; 5 6 const uart = pi.devices.mini_uart; 7 8 pub fn main() !void { 9 const w = &uart.writer; 10 const r = &uart.reader; 11 12 var buffer: [1024 * 1024]u8 = undefined; 13 var fba: std.heap.FixedBufferAllocator = .init(&buffer); 14 var allocator = fba.allocator(); 15 16 try tcp.send(w, .{ .Bind = .{ .port = 8080, .ttl = 0 } }); 17 18 while (true) { 19 switch (try tcp.receive(r, allocator)) { 20 .Request => |*request| { 21 const ip: *const [4]u8 = @ptrCast(&request.ip); 22 const msg = try std.fmt.allocPrint(allocator, "got connection {d}: {d}.{d}.{d}.{d}", .{ request.id, ip[3], ip[2], ip[1], ip[0] }); 23 try tcp.send(w, .{ .Print = .{ .data = msg, .length = @truncate(msg.len) } }); 24 allocator.free(msg); 25 }, 26 .Write => |*write| { 27 const msg = try std.fmt.allocPrint(allocator, "read {d}: {s}", .{ write.id, write.data }); 28 try tcp.send(w, .{ .Print = .{ .data = msg, .length = @truncate(msg.len) } }); 29 allocator.free(msg); 30 31 try tcp.send(w, .{ .Write = .{ .data = write.data, .length = write.length, .id = write.id } }); 32 }, 33 .Disconnect => |connection| { 34 const msg = try std.fmt.allocPrint(allocator, "lost connection {d}", .{connection}); 35 try tcp.send(w, .{ .Print = .{ .data = msg, .length = @truncate(msg.len) } }); 36 allocator.free(msg); 37 }, 38 else => {}, 39 } 40 } 41 }