Handle network blocking well

This commit is contained in:
2025-04-06 11:03:16 -04:00
parent 8278648ba9
commit 6eef36e78a
2 changed files with 7 additions and 6 deletions

View File

@@ -32,9 +32,9 @@ pub fn main() !void {
// _ = try Saprus.sendInitialConnection(if (message.items.len > 0) message.items else "Hello darkness my old friend", 6868, gpa); // _ = try Saprus.sendInitialConnection(if (message.items.len > 0) message.items else "Hello darkness my old friend", 6868, gpa);
const res = Saprus.connect(if (message.items.len > 0) message.items else "Hello darkness my old friend", gpa) catch |err| { const res: ?SaprusMessage = Saprus.connect(if (message.items.len > 0) message.items else "Hello darkness my old friend", gpa) catch |err| switch (err) {
std.debug.print("Error: {s}", .{@errorName(err)}); error.WouldBlock => null,
return; else => return err,
}; };
defer if (res) |r| r.deinit(gpa); defer if (res) |r| r.deinit(gpa);
if (res) |r| { if (res) |r| {
@@ -52,3 +52,4 @@ const DebugAllocator = std.heap.DebugAllocator(.{});
const ArrayList = std.ArrayList; const ArrayList = std.ArrayList;
const Saprus = @import("./saprus.zig"); const Saprus = @import("./saprus.zig");
const SaprusMessage = Saprus.SaprusMessage;

View File

@@ -98,13 +98,13 @@ pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage {
}; };
// timeout 1s // timeout 1s
try sock.setReadTimeout(1_000_000); try sock.setReadTimeout(1 * std.time.us_per_s);
try sock.bind(bind_addr); try sock.bind(bind_addr);
const msg = try sendInitialConnection(payload, initial_port, allocator); const msg = try sendInitialConnection(payload, initial_port, allocator);
var response_buf: [4096]u8 = undefined; var response_buf: [4096]u8 = undefined;
_ = try sock.receive(&response_buf); _ = try sock.receive(&response_buf); // Ignore message that I sent.
const len = try sock.receive(&response_buf); const len = try sock.receive(&response_buf);
initial_conn_res = try SaprusMessage.fromBytes(response_buf[0..len], allocator); initial_conn_res = try SaprusMessage.fromBytes(response_buf[0..len], allocator);
@@ -115,7 +115,7 @@ pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage {
return initial_conn_res; return initial_conn_res;
} }
const SaprusMessage = @import("./saprus_message.zig").SaprusMessage; pub const SaprusMessage = @import("./saprus_message.zig").SaprusMessage;
const std = @import("std"); const std = @import("std");
const Random = std.Random; const Random = std.Random;