Skip to content

Instantly share code, notes, and snippets.

@Luukdegram
Created January 30, 2021 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Luukdegram/215e27d2455eff53a177aff55dde7b47 to your computer and use it in GitHub Desktop.
Save Luukdegram/215e27d2455eff53a177aff55dde7b47 to your computer and use it in GitHub Desktop.
Example server
const std = @import("std");
const net = std.net;
pub const io_mode = .evented;
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = &gpa.allocator;
try run(alloc);
}
fn run(gpa: *std.mem.Allocator) !void {
var server = net.StreamServer.init(.{ .reuse_address = true });
try server.listen(try net.Address.parseIp("0.0.0.0", 8080));
var clients = std.atomic.Queue(*Client).init();
while (true) {
const conn = try server.accept();
const client = try gpa.create(Client);
client.* = .{
.stream = conn.stream,
.node = .{ .data = client },
.frame = async client.handle(gpa, &clients),
};
while (clients.get()) |node| {
const c = node.data;
await c.frame catch {};
c.stream.close();
gpa.destroy(c);
}
}
}
const Client = struct {
frame: @Frame(handle),
stream: net.Stream,
node: std.atomic.Queue(*Client).Node,
fn handle(self: *Client, gpa: *std.mem.Allocator, clients: *std.atomic.Queue(*Client)) !void {
defer clients.put(&self.node);
while (true) {
var buf: [512]u8 = undefined;
const read = try self.stream.reader().read(&buf);
if (read == 0) break;
try self.stream.writer().writeAll("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello Zig!");
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment