Serve 5 clients before quitting

This commit is contained in:
2025-11-13 23:54:06 -05:00
parent 6cfaba958e
commit 6e8d016f2f

View File

@@ -90,10 +90,13 @@ const ServerInfo = struct {
}; };
fn serverMain(gpa: std.mem.Allocator, iter: *std.process.ArgIterator, main_args: MainArgs) !void { fn serverMain(gpa: std.mem.Allocator, iter: *std.process.ArgIterator, main_args: MainArgs) !void {
_ = gpa;
_ = iter; _ = iter;
_ = main_args; _ = main_args;
var threaded: std.Io.Threaded = .init(gpa);
defer threaded.deinit();
const io = threaded.io();
const info: ServerInfo = .{ const info: ServerInfo = .{
.server_id = "foo", .server_id = "foo",
.server_name = "bar", .server_name = "bar",
@@ -101,12 +104,41 @@ fn serverMain(gpa: std.mem.Allocator, iter: *std.process.ArgIterator, main_args:
.max_payload = 6969, .max_payload = 6969,
}; };
var out_fs = std.fs.File.stderr().writer(&.{}); var server = try std.Io.net.IpAddress.listen(.{
const out = &out_fs.interface; .ip4 = .{
.bytes = .{ 0, 0, 0, 0 },
.port = info.port,
},
}, io, .{});
defer server.deinit(io);
try std.json.Stringify.value(info, .{ var group: std.Io.Group = .init;
.whitespace = .indent_2, defer group.wait(io);
}, out); for (0..5) |_| {
const stream = try server.accept(io);
std.debug.print("in serverMain\n", .{}); group.async(io, handleConnection, .{ io, stream, info });
}
// var buffer: [1024]u8 = undefined;
// var out_fs = std.fs.File.stderr().writer(&buffer);
// const out = &out_fs.interface;
}
fn handleConnection(io: std.Io, stream: std.Io.net.Stream, info: ServerInfo) void {
defer stream.close(io);
var buffer: [1024]u8 = undefined;
var writer = stream.writer(io, &buffer);
const out = &writer.interface;
writeInfo(out, info) catch |err| {
std.debug.print("failed to write to client: {}\n", .{err});
};
}
fn writeInfo(out: *std.Io.Writer, info: ServerInfo) !void {
defer out.flush() catch {};
_ = try out.write("INFO ");
try std.json.Stringify.value(info, .{}, out);
_ = try out.write(&.{ 0x0D, 0x0A });
} }