Accepting net clients asynchronously with new std.Io

Heya !

Any idea how I would implement in zig’s std.Io.net accepting clients asynchronously ?
I used to set force_nonblocking in std.net.Address.ListenOptions and handle it from there.

However, it was deleted as std.Io as the new way to do Io things. As such, how would you idiomatically, using the new interface, force non-blocking client acceptance ? I would prefer if the solution doesn’t include spawning a new thread only for accepting clients.

In more details, I am remaking a minecraft server in TCP and I would need to be able to do ticks during other Io things. I am already quite well versed in the recents merges in Io and its internal workings (such as operate etc.). As such, I’m able to control the std.Io interface that I’m using if needed.

Thanks in advance !

To be more precise, I’m maxing out the threads but one of the machine already for physics, AI, etc. So I would like to avoid wasting a thread on just accepting clients.


My current setup is akin to :

const Config = @import("Config.zig");
const std = @import("std");

server: std.Io.net.Server,
allocator: std.mem.Allocator,
io: std.Io,
stopping: std.atomic.Value(bool),

pub fn init(allocator: std.mem.Allocator, io: std.Io) !@This() {
    const addr: std.Io.net.IpAddress = try .parse(Config.config.network.ip, Config.config.network.port);
    return .{
        .stopping = .init(false),
        .server = addr.listen(io, .{}),
        .allocator = allocator,
        .io = io,
    };
}

pub fn deinit(self: *@This()) void {
    self.server.deinit(self.io);
}

pub fn start(self: *@This()) void {
    while (self.stopping.load(.acquire)) {
          // I would like to check if
          // is a client connected :
          // handle accept or else
         self.tick();
    }
}

fn tick(self: *@This()) void {
    // Do other stuff
}

sounds to me like you want that last thread to be running a single-threaded instance of std.Io.Evented. I believe that’s precisely one of the design goals for that type, but you might have to do a little reading of the code to see to what extent that needs your configuration and/or is ready to go on master.

1 Like