Created
January 30, 2021 10:59
-
-
Save Luukdegram/215e27d2455eff53a177aff55dde7b47 to your computer and use it in GitHub Desktop.
Example server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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