From f3fe9b60d20b5b2e2a08ec0de0fca506c03f35e7 Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 19 Dec 2022 22:50:01 -0300 Subject: [PATCH] add receive buffers to prevent stuttering --- src/main.zig | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/main.zig b/src/main.zig index dd70aef..1227401 100644 --- a/src/main.zig +++ b/src/main.zig @@ -47,17 +47,33 @@ pub fn main() !void { var to_sock = try network.Socket.create(.ipv4, .udp); defer to_sock.close(); - var receive_buffer: [2048]u8 = undefined; - while (true) { - const reader = from_sock.reader(); - const received_bytes = try reader.read(&receive_buffer); - const bytes = receive_buffer[0..received_bytes]; - const sent_bytes = try to_sock.sendTo(to, bytes); - if (sent_bytes != received_bytes) { - logger.warn( - "tried to send {d} bytes, actually sent {d}", - .{ received_bytes, sent_bytes }, - ); + const BUFSIZE = 4; + const Buffer = struct { + raw_data: [2048]u8, + message: []u8, + }; + + var receive_buffers: [BUFSIZE]Buffer = undefined; + var receive_buffer_index: usize = 0; + + const reader = from_sock.reader(); + + while (true) : (receive_buffer_index += 1) { + const array_index = receive_buffer_index % BUFSIZE; + const raw_data = &receive_buffers[array_index].raw_data; + const received_bytes = try reader.read(raw_data); + receive_buffers[array_index].message = raw_data[0..received_bytes]; + + if (receive_buffer_index > BUFSIZE) { + const index_to_send = (receive_buffer_index - BUFSIZE - 1) % BUFSIZE; + const bytes_to_send = receive_buffers[index_to_send].message; + const sent_bytes = try to_sock.sendTo(to, bytes_to_send); + if (sent_bytes != received_bytes) { + logger.warn( + "tried to send {d} bytes, actually sent {d}", + .{ received_bytes, sent_bytes }, + ); + } } } }