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,17 +47,33 @@ 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 {
const reader = from_sock.reader(); raw_data: [2048]u8,
const received_bytes = try reader.read(&receive_buffer); message: []u8,
const bytes = receive_buffer[0..received_bytes]; };
const sent_bytes = try to_sock.sendTo(to, bytes);
if (sent_bytes != received_bytes) { var receive_buffers: [BUFSIZE]Buffer = undefined;
logger.warn( var receive_buffer_index: usize = 0;
"tried to send {d} bytes, actually sent {d}",
.{ received_bytes, sent_bytes }, 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 },
);
}
} }
} }
} }