add receive buffers to prevent stuttering

This commit is contained in:
Luna 2022-12-19 22:50:01 -03:00
parent 49de461f1d
commit f3fe9b60d2

View file

@ -47,12 +47,27 @@ pub fn main() !void {
var to_sock = try network.Socket.create(.ipv4, .udp); var to_sock = try network.Socket.create(.ipv4, .udp);
defer to_sock.close(); defer to_sock.close();
var receive_buffer: [2048]u8 = undefined; const BUFSIZE = 4;
while (true) { 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(); const reader = from_sock.reader();
const received_bytes = try reader.read(&receive_buffer);
const bytes = receive_buffer[0..received_bytes]; while (true) : (receive_buffer_index += 1) {
const sent_bytes = try to_sock.sendTo(to, bytes); 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) { if (sent_bytes != received_bytes) {
logger.warn( logger.warn(
"tried to send {d} bytes, actually sent {d}", "tried to send {d} bytes, actually sent {d}",
@ -61,3 +76,4 @@ pub fn main() !void {
} }
} }
} }
}